Maybe I’m late to the party, but I just found the Except() LINQ extension method. I knew I loved .NET!
For those of you familiar with set theory, this returns the “difference” between two collections. In my case, I needed to append a set of items to an existing collection, but only if they’re not already in the target collection. This thing was just what I needed.
Here’s the definition:
// // Summary: // Produces the set difference of two sequences by using the default equality // comparer to compare values. // // Parameters: // first: // An System.Collections.Generic.IEnumerable<T> whose elements that are not // also in second will be returned. // // second: // An System.Collections.Generic.IEnumerable<T> whose elements that also occur // in the first sequence will cause those elements to be removed from the returned // sequence. // // Type parameters: // TSource: // The type of the elements of the input sequences. // // Returns: // A sequence that contains the set difference of the elements of two sequences. // // Exceptions: // System.ArgumentNullException: // first or second is null. public static IEnumerable<TSource> Except<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second);
Couple this with the ToList() and ForEach() extension method, and you can do this work in about 2 lines of code. Love it!