Muhid Muhid - 2 months ago 16
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))
Console.WriteLine(s);
}


When run it produces the following output

b
c


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

a
b
c
d


Shouldn't this be

a
d


if I change the if condition to

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


I get

a
d


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
secondSample
is not in sample

Answer

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))
           Console.WriteLine(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