Muhid Muhid - 1 year ago 124
C# Question

linq Any operator with not equal(!=)

I'm having trouble understanding the linq any operator. Lets consider the following snippet of code (using VS 2010 and .Net 4.0)

List<string> sample = new List<string> { "a", "b", "c", "d" };
List<string> secondSample = new List<string> { "b", "c" };

foreach (string s in sample)
if(secondSample.Any(data=> data.ToString() == s))

When run it produces the following output


Which is what I'm expecting. However if I change the equality operator(
) to Not Equal(
) I get this


Shouldn't this be


if I change the if condition to

if(!(secondSample.Any(data=> data.ToString() == s)))

I get


So my question is am I interpreting the the Any operator in the wrong way? Shouldn't

if(secondSample.Any(data=> data.ToString() != s))

evaluate to true when values from
is not in sample

Answer Source

If you want to use != operator and you expect a d as the result then you should use All not Any:

 if(secondSample.All(data=> data.ToString() != s))

Explanation secondSample.Any(data=> data.ToString() != s) will be true if just one element in secondSample was not equal to the given data item (in your sample list), so in your case it will be always true and you see all elements is written in the console.

Better Solution having two array A and B, if you want those A element which are not in B using LINQ you can can try Except and if you are looking for common elements you may try Intersect:

List<string> A = new List<string> { "a", "b", "c", "d" };
List<string> B= new List<string> { "b", "c" };

var AnotInB = A.Except(B).ToList(); //a , d

var AInB = A.Intersect(B).ToList(); //b, c
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download