I am creating a LINQ query and I wa开发者_StackOverflow社区nt to have a SQL-style NOT IN clause to make sure that my result does not have one of the values from a comma separated list.
I could not find a NOT IN clause for LINQ. Please suggest a solution.
You need to do a !contains on the collection of objects that you want to exclude.
var excluded = new[] { 3, 7, 19, 41 };
var v = from i in Enumerable.Range(0, 100)
where !excluded.Contains(i)
select i;
You'll want the .Except() set operator.
var results = list1.Except(list2);
http://blogs.msdn.com/b/charlie/archive/2008/07/12/the-linq-set-operators.aspx http://www.hookedonlinq.com/ExceptOperator.ashx
Note: You'll have to implement an iEqualityComparor to use the Except method with complex types.
Something like this...
string items = "1,2,3,4";
var subList = items.Split(',');
var result = list.Where(item=>!subList.Contains(item.SomeStringField));
精彩评论