我会使用普通的 LINQ 像下面这样实现它:
public static IQueryable<T> Exclude<T>(this IQuerable<T> qry, Expression<Func<T, int>> keySelector, List<int> excludedItems)
{
var keyGroups = qry.GroupBy(keySelector);
var includedGroups = keyGroups.Where(g => !excludedItems.Contains(g.Key));
return includedGroups.SelectMany(g => g);
}
然后它可以像这样使用:
public class MyClass
{
public int Key { get; set; }
}
IQueryable<MyClass> source = // Get source data (DataContext/ObjectContext/ISession etc.)
var excludedKeys = new List<int> { 1, 3, 11 };
var result = source.Exclude(item => item.Key, excludedKeys);
动态 LINQ 更新
IQuerable GetItemsWithoutExcluded(IQuerable qry, string primaryKey, List<int> excludedItems)
{
if(excludedItems.Count == 0)
return qry;
var keyChecks = excludedItems.Select(i => String.Format("p.{0} != {1}", primaryKey, i));
var constraint = String.Join(" && ", keyChecks )
return qry.Where("p => " + constraint);
}