我想为可变数量的列创建动态where子句。可以这样做吗?
我想我已经查看了与此主题相关的所有帖子,但仍无法找到答案。
var results = from table1 in dt1.AsEnumerable()
join table2 in dt2.AsEnumerable() on table1.Field<int>("ID") equals table2.Field<int>("ID")
where table1["ColumnA"].ToString() != table2["ColumnA"].ToString() ||
table1["ColumnB"].ToString() != table2["ColumnB"].ToString() ||
table1["ColumnC"].ToString() != table2["ColumnC"].ToString()
select table1;
答案 0 :(得分:0)
您可以在逻辑上添加where子句。这是一个扩展方法 (这不是我的,很久以前我在StackOverflow的某个地方看过它。当我找到它时我会引用它)
Func<T, bool> And(this Func<T, bool> a, Func<T, bool> b)
{
return (T x) => a(x) && b(x);
}
有了它,你可以迭代列并将它们添加到where子句:
Func<string, bool> whereClause = x => true;
foreach(string columnName in dt.Columns.Select(x => x.ColumnName)
{
string first = dt.Columns[columnName].ToString();
string second = dt2.Columns[columnName].ToString();
whereClause = whereClause.And(x => first.Equals(second));
}
var result = (from foo in bar select fooBar).Where(whereClause);
答案 1 :(得分:0)
如果是动态where子句,您可以使用System.Linq.Dynamic
(ScottGu's blog article和nuget):
var results = (from fruit in fruits
join car in cars on fruit.Id equals car.Id
select new { fruit, car })
.AsQueryable()
.Where("fruit.ColA != car.ColA")
.Where("fruit.ColB == car.ColB");
或者使用@ joe-albahari编写的extensions from PredicateBuilder
动态构建表达式。例如:
var predicate =
PredicateBuilder
.True<Tuple<Product, Product>>()
.And(t => t.Item1.ColA != t.Item2.ColA)
.And(t => t.Item1.ColB == t.Item2.ColB)
.Compile();
(from fruit in fruits
join car in cars on fruit.Id equals car.Id
select Tuple.Create(fruit, car))
.Where(predicate)
.Dump();
ps:gisthub
提供完整代码