tags:

views:

53

answers:

3

Linq is great, but it always seems to confuse me a bit.

This is my latest confusion:

Say I have two List<String> objects. We will call them sourceList and destList.

I need a way to find the list of strings that are in sourceList and not in destList AND find the list of strings that are in destList and not in SourceList.

This is a bit confusing so here is the example:

  sourceList    destList
   Orange    
   Apple          Apple
   Grape          Grape
                  Kiwi
                  Banana

So the first result I am looking for would be a list with Orange in it. The second result would the a list with Kiwi and Banana in it.

Any idea how to do that with Linq?

+4  A: 
sourceList.Except(destList)

Should get a difference of source and dest. You can also do the reverse and combine.

sukru
http://www.hookedonlinq.com/ExceptOperator.ashx is a good example of the Except method. There is an overload that allows you to create your own comparison function. Not needed in this case but could be useful other situations.
mpenrow
+3  A: 

I was just doing this earlier today actually. As sukru said this code should do it for you:

List<string> firstResultList = sourceList.Except(destList);
List<string> secondResultList = destList.Except(sourceList);

firstResultList will have Orange in it and secondResultList will have Kiwi and Banana.

jb
+1  A: 

The Except<>-Method is your way to go.

var result1 = sourceList.Except(destList); // will give you the orange

var result2 = destList.Except(sourceList); // will give you the kiwi and the banana

The method also takes an IEqualityComparer<> as second parameter, which compares the elements in the lists. This can be important, for example, when comparing custom types. For the Strings, you could use the StringComparer-Class if neccesary, which implements IEqualityComparer.

There are also a lot other usefull methods in LINQ, for example Intersect:

var result2 = sourcelist.Intersect(destList); // will give you Apple and Grape
dkson