问题:取数据库表中DateTime类型字段时,截取年份子串,去除重复字段,如何处理?
方法:使用Linq中的Lambda表达式,可以轻松实现,以下是简单的示例代码:
public void BindNF()
{
//这里要去除相同的年份,通过Linq的Lambda表达式实现
DM dm = new DM();
string strSQL = "select * from [预警记录] ";
DataSet ds = dm.getsql(strSQL);
ArrayList al = new ArrayList();
foreach (DataRowView drv in ds.Tables[0].DefaultView)
{
al.Add(drv["发布时间"].ToString().Substring(0, drv["发布时间"].ToString().IndexOf("-")));
}
//构造泛型集合
List<string> years = new List<string>();
for (int i = 0; i < al.Count; i++)
{
years.Add(al[i].ToString());
}
//Distinct()方法用于返回序列中的非重复元素
var result = years.Distinct();
this.ddlNF.DataSource = result;
this.ddlNF.DataBind();
}
2、另外一种非LINQ实现方法,利用普通的循环比较方法也可以实现: