Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq Any operator with not equal(!=)

Tags:

c#

.net

list

linq

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

like image 845
Muhid Avatar asked Nov 29 '25 02:11

Muhid


2 Answers

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
like image 77
Hossein Narimani Rad Avatar answered Dec 01 '25 16:12

Hossein Narimani Rad


!= in an Any means ALL are not equal.

So you read if there is Any that is not equal, then you can print. And guess what, you always have at least 1 that is not equal. That's why you get all the answers.

in your other statement you say: the one that is not equal you can print...

any clearer?

like image 45
Roelant M Avatar answered Dec 01 '25 16:12

Roelant M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!