3

Possible Duplicate:
Comparing two collections for equality

I have two lists

List<int> Foo = new List<int>(){ 1, 2, 3 };

and

List<int> Bar = new List<int>(){ 2, 1 };

To find out if they have same elements or not I did

if(Foo.Except(Bar).Any() || Bar.Except(Foo).Any())
{
    //Do Something
}

but this requires two bool evaluations. First it does Foo.Except(Bar).Any() and then Bar.Except(Foo).Any(). Is there a way to do this in single evaluation?

Community
  • 1
  • 1
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
  • What is expected result - to find if there is any same element in both collections, or to find if all elements in collections are same (but possibly in different order)? – Sergey Berezovskiy Nov 24 '12 at 10:16
  • @lazyberezovsky: order is not important. just to check if any element is there in Foo and not in Bar or is in Bar and not in Foo. – Nikhil Agrawal Nov 24 '12 at 10:29

2 Answers2

1
        var sharedCount = Foo.Intersect(Bar).Count();
        if (Foo.Distinct().Count() > sharedCount || Bar.Distinct().Count() > sharedCount)
        {
            // there are different elements
        }
        {
            // they contain the same elements
        }
armen.shimoon
  • 6,303
  • 24
  • 32
-4

You don't have to check it twice. Just do something like this (pay attention to Foo, it can be null and throw the related exception)

if(Foo.Intersect(Bar).Any())
{
    //Do Something
}

You might also want to check first you have to check if one of those lists or both are empty or null.. but only if that situation has any particular value for you.

Salaros
  • 1,444
  • 1
  • 14
  • 34