PredicateBuilder返回零记录 [英] PredicateBuilder returning zero records
问题描述
我正在使用PredicateBuilder创建动态的Where子句以从DataTable查询数据.我有一个字典,其中包含我需要搜索的列名和值.我只是简单地遍历字典,如果键与列名匹配,则将该键和值添加到谓词中.在对数据表运行实际查询之前,一切似乎都正常,我得到了零条记录:(但是,如果我用p => p ["Year"] =="2010"之类的东西代替动态谓词,则会得到记录返回.这是代码:
I'm using PredicateBuilder to create a dynamic Where clause to query data from a DataTable. I have a Dictionary that contains my column names and values I need to search for. I'm simply iterating over the dictionary, if the key matches a column name, then add that key and value to the predicate. Everything seems to work fine until the actual query is run against the datatable, I get zero records back:( But if I replace the dynamic predicate with something like p => p["Year"] == "2010", I get records back. Here's the code:
var objectList = table.AsEnumerable();
Func<DataRow, bool> predicate = GetPredicate(parms, table.Columns);
var list1 = objectList.Where(predicate).ToList();
private static Func<DataRow, bool> GetPredicate(Dictionary <string, string> parms, DataColumnCollection dataColumnCollection)
{
var predicate = PredicateBuilder.False<DataRow>();
foreach (var parm in parms)
{
if (dataColumnCollection.Contains(parm.Key))
{
var copy = parm;
predicate = predicate.And(p => p[copy.Key] == copy.Value);
}
}
return predicate.Compile();
}
任何帮助将不胜感激:)
Any help would be greatly appreciated:)
推荐答案
您先从false
开始,然后添加and
子句.
You're starting with false
and then adding and
clauses.
false && ...
始终返回false
,因此您的Where
子句将永远不匹配任何内容.
false && ...
always returns false
, so your Where
clause will never match anything.
尝试以
var predicate = PredicateBuilder.True<DataRow>();
也:
ALSO:
您正在关闭循环变量,这意味着您的所有谓词都将使用parms
中的最后一个parm
.
You are closing over a loop variable, which means all your predicates will use the last parm
in parms
.
您可以通过在循环中创建本地副本来解决此问题:
You can fix this by creating a local copy in your loop:
foreach( var parm in parms )
{
if (dataColumnCollection.Contains(parm.Key))
{
var copy = parm;
predicate = predicate.And( p => p[ copy.Key ] == copy.Value );
}
更新:
DataRow[ key ]
的类型为object
,因此在p[ copy.Key ] == copy.Value
中,相等运算符是对象引用相等,而不是字符串相等.
DataRow[ key ]
is of type object
, so in p[ copy.Key ] == copy.Value
, the equality operator is object reference equality, not string equality.
您可以通过指定String.Equals
来解决此问题:
You can fix this by specifying String.Equals
:
predicate = predicate.And( p => String.Equals( p[ copy.Key ], copy.Value ) );
有趣的是,此示例显示您可以具有内容相同的string
的多个实例.
Interestingly, this example shows that you can have multiple instances of string
with the same contents.
这篇关于PredicateBuilder返回零记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!