当使用下面的方法进行 OR 操作时,我得到了重复的记录。我必须指定一个自定义的 IEqualityComparer 吗?一个简单的 distinct() 不起作用
internal static IQueryable<T> FilterEntity<T>(filters filters, IQueryable<T> entities)
{
if (filters.groupOp == "AND")
foreach (var rule in filters.rules)
entities = entities.Where<T>(
rule.field, rule.data,
(WhereOperation)StringEnum.Parse(typeof(WhereOperation), rule.op)
);
else
{
//Or
IQueryable<T> temp = (new List<T>()).AsQueryable();
foreach (var rule in filters.rules)
{
var t = entities.Where<T>(
rule.field, rule.data,
(WhereOperation)StringEnum.Parse(typeof(WhereOperation), rule.op)
);
temp = temp.Concat<T>(t).AsQueryable();
}
entities = temp;
}
return entities;
}
在下面@usr 的建议后编辑-这给了我在sql profiler 中的正确查询(有一个不同的),但这开始看起来太复杂了-我想要一个更干净的解决方案
internal static IQueryable<T> FilterEntity<T>(filters filters, IQueryable<T> entities)
{
if (filters.groupOp == "AND")
foreach (var rule in filters.rules)
entities = entities.Where<T>(
rule.field, rule.data,
(WhereOperation)StringEnum.Parse(typeof(WhereOperation), rule.op)
);
else
{
//Or
var t1 = entities.Where<T>(filters.rules[0].field,filters.rules[0].data,
(WhereOperation)StringEnum.Parse(typeof(WhereOperation),filters.rules[0].op)
);
for (int i = 1; i<filters.rules.Count(); i++)
{
var t = t1.Where<T>(filters.rules[i].field, filters.rules[i].data,
(WhereOperation)StringEnum.Parse(typeof(WhereOperation), filters.rules[i].op)
);
t1.Concat<T>(t).AsQueryable();
}
entities = t1;
}
return entities.Distinct<T>();
}