01/09/11

Compare two collections with Linq and method Except

Suppose to have two collections of objects and you want to get the objects of the first collection that are not included in the second collection, you can use Linq with the method "Except".

Let's show a simple example:


            double[] numbers1 = { 2.0, 2.1, 2.2, 2.3, 2.4, 2.5 };
            double[] numbers2 = { 2.2 };

            IEnumerable onlyInFirstSet = numbers1.Except(numbers2);
Now onlyInFirstSet will contains only numbers that are not present in the secondo collection.

You can get the inverse calling the method Expect on the collection numbers2 and passing the parameter numbers1.

Remember that If you want to compare sequences of objects of some custom data type, you need to implement che interface IEquatable<T> where T is your object.

This interface require to implement the methods Equals and GetHashCode.
In the method Equals you define the logic that let the program to know when two object are equals.

In the method GetHashCode you implement the hash code: it is a numerical value that is tied to a fixed input and it is a form of one-way encryption, let you uniquely identifying an object.

0 commenti:

Posta un commento

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Grants For Single Moms