我正在使用 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();
任何建议都会有所帮助。
最佳答案
此代码返回 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();
关于c# - 从 Linq 中的数据表中选择不同的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39272363/