我使用linq查询从数据表中选择2个不同的列id和name。我已经使用了下面的代码,但它的投掷错误特定广告无效。
sdatatable = ds.Tables[0].AsEnumerable().Where(x => x.Field<string>
("TableName") == "header").CopyToDataTable();
rptcourse.DataSource = sdatatable.AsEnumerable().Select(row => new
{
locationid = row.Field<string>("locationID"),
locationname = row.Field<string>("locationname")
}).Distinct();
任何建议都有帮助。
答案 0 :(得分:5)
此代码返回IEnumerble<T>
,而DataSource
可能需要List<T>
。在ToList()
之后添加Distinct()
:
rptcourse.DataSource = sdatatable.AsEnumerable().Select(row => new
{
locationid = Convert.ToInt32(row["locationid"]),
locationname = row.Field<string>("locationname")
}).Distinct().ToList();
您也可以这样加入两个查询:
rptcourse.DataSource = ds.Tables[0].Where(x => x.Field<string>("TableName") == "header")
.Select(row => new
{
locationid = Convert.ToInt32(row["locationid"])
locationname = row.Field<string>("locationname")
})
.Distinct().ToList();