我想对多个级别使用distinct子句。首先,我尝试使用DataTable,但未成功,因此我将DataTable转换为AsEnumerable。
我的问题是我指定/硬编码的字段将变得动态,这与Where&Select相同。
如何在Where
和Select
中添加动态字段?
DataTable data3 = new DataTable();
var listData = data3.AsEnumerable()
.Where(m => !String.IsNullOrEmpty(m.Field<string>("clientname"))
&& !String.IsNullOrEmpty(m.Field<string>("project"))
&& !String.IsNullOrEmpty(m.Field<string>("postedstate"))
&& !String.IsNullOrEmpty(m.Field<string>("postedcity"))
&& !String.IsNullOrEmpty(m.Field<string>("siteadd")))
.Select(row => new
{
clientname = row.Field<string>("clientname"),
project = row.Field<string>("project"),
postedstate = row.Field<string>("postedstate"),
postedcity = row.Field<string>("postedcity"),
siteadd = row.Field<string>("siteadd")
}).Distinct();
答案 0 :(得分:0)
您可以执行以下操作:
string clientName = "my client";
string project = null;
DataTable data3 = new DataTable();
var listData = data3.AsEnumerable().Where(m =>
(String.IsNullOrEmpty(clientName) || m.Field<string>("clientname") == clientName)
&& (String.IsNullOrEmpty(project) || m.Field<string>("project") == project)
).Select(row => new Project()
{
clientname = row.Field<string>("clientname"),
project = row.Field<string>("project"),
postedstate = row.Field<string>("postedstate"),
postedcity = row.Field<string>("postedcity"),
siteadd = row.Field<string>("siteadd")
}).Distinct();
这样,您将无需返回匿名类型并摆脱问题。