Archive for June, 2011

C# equality

June 3, 2011

Look at the following three and see if you can figure out which one works correctly for finding any single common item in a set:

1) Permissions.Intersect(permissions).Any();
2) Permissions.Any(p => permissions.Contains(p));
3) (from p in Permissions from p1 in permissions where p1.Equals(p) select p).Any();

Note that I’m trying to do comparison on the Equals method, not by reference.

If you guessed that I posted these in the order I tried, you win. The third try was the one that finally allowed me to compare two groups to find if there were any common items. I’m kind of annoyed that I had to go through these three iterations. It’s always a crapshoot whether methods will compare by reference, equality or the Equals() method.