As a part of the infrastructure introduced in .NET 3.5 to support the various flavours of LINQ, there are a whole heap of generic extension methods that are available whenever you have IEnumerable<T>.

Two that I’ve found useful recently are Intersect() and Except() - both of these work to filter values out of the sequence.

A couple of examples are the best way to understand them:

// Returns all multiples of three
IEnumerable<int> multiplesOfThree = ...;
// 3, 6, 9, 12, 15, 18, 21, ...

// Returns all multiples of four
IEnumerable<int> multiplesOfFour = ...;
// 4, 8, 12, 16, 20, 24, ...

// Returns multiplesOfThree that are NOT multiplesOfFour
IEnumerable<int> exceptExample = multiplesOfThree.Except(multiplesOfFour);
// 3, 6, 9, 15, 18, 21, 27 ...

// Returns multiplesOfThree that ARE multiplesOfFour
IEnumerable<int> intersectExample = multiplesOfThree.Intersect(multiplesOfThree);
// 12, 24, 36, 48 ...

If you haven’t already, check out the members of Enumerable on MSDN - well worth the effort.

Comments

blog comments powered by Disqus
Next Post
Living with StyleCop  25 Jul 2008
Prior Post
Software Development Meme  19 Jul 2008
Related Posts
Types behaving badly  14 Apr 2018
Implementing Value Equality  07 Apr 2018
Implementing Entity Equality  31 Mar 2018
Equality and GetHashCode  24 Mar 2018
Types of Equality  10 Mar 2018
Why is Equality important in .NET?  03 Mar 2018
Invalid Build Configuration: Debug|BNB  14 May 2011
Streams in .NET  26 Dec 2003
Bitmap cloning in .NET  11 Dec 2003
Streams in .NET  20 Nov 2003
Related Pages
July 2008 archive