1

假设我是Member我不想包含的名称的实体和列表。

var excludeNames = new [] { "A","B","C","D"};

var members = db.Members.Except(excludeNames);

或者

 var excludeNames = new[]{ "A","B","C","D"};
 var Members = db.Members.Where(m=> excludeNames.Where(xcl => xcl != m.Name));

这些都不起作用。我也试过这个:

 var excludeNames = new[] { "A","B","C","D"};
 var members = from m in db.Members
               from xcl in excludeNames
               where m.Name != xcl
               select m;
4

2 回答 2

7

尝试以下操作:

var excludeNames = new[] { "A","B","C","D"};
var members = from m in db.Members
              where !excludeNames.Contains(m.Name)
              select m;

请注意,即使 LINQ 允许您以多种方式表达查询,您仍然需要考虑您的查询需要转换为 SQL 的事实。Entity Framework 支持的 SQL 方言将值列表与行集区别对待。

例如,您要在 SQL 中构建的查询将是

SELECT *
FROM Members AS m
WHERE m.name NOT IN ('A', 'B', 'C', 'C')

x IN (list)SQL 中的一个转换为list.Contains(x)LINQ 中的。)

例如,你不能说类似的话

SELECT *
FROM Members AS m
WHERE EXISTS(SELECT 1
             FROM ('A', 'B', 'C', 'C') AS xcl
             WHERE m.name != xcl)

也不

SELECT *
FROM Members AS m,
     ('A', 'B', 'C', 'C') AS xcl
WHERE m.name != xcl

根本不允许这些查询。尽管 Entity Framework 在将 LINQ 查询转换为 SQL 时可以非常智能,但它确实有其局限性。

于 2012-05-07T21:54:08.050 回答
1

我认为这可能是一个很好的解决方案。

var excludeNames = new [] { "A","B","C","D"};

var members = db.Members.Where(member => excludeNames.Any(member.Name) == false).ToList() ;

//or     
var excludeNames = new [] { "A","B","C","D"};

var members = db.Members.Where(member => !excludeNames.Any(member.Name)).ToList() ;
于 2015-05-24T11:55:43.697 回答