How to remove items from an enumerable object that are equal to items of another enumerable object

Let’s say we have two integer arrays:

int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }
int[] b = { 3, 4, 5, 8, 9, 10, 45 }

C# provides a handy extension method that we can call that will compare the two arrays and then return a new enumerable object that will only contain integers from “a” that are NOT in “b”.

Example:

void Main()
{
 int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
 int[] b = { 3, 4, 5, 8, 9, 10, 45 };

 // Remove items from "a" that are not in "b"
 var c = a.Except(b);
 foreach(int i in c)
 {
 Console.WriteLine(i);
 }

 Console.WriteLine("--------");

 // Remove items from "b" that are not in "a"
 c = b.Except(a);
 foreach(int i in c)
 {
 Console.WriteLine(i);
 }
}

As you can see in the code above, the handy extension method is called “Except”. The formal definition of this extension method is:

Enumerable.Except(Of TSource) Method (IEnumerable(Of TSource), IEnumerable(Of TSource))
Produces the set difference of two sequences by using the default equality comparer to compare values.

Namespace: System.Linq
Assembly: System.Core (in System.Core.dll)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s