Caveman's Blog

My commitment to learning.

Linq: Contains operator

leave a comment »

The Contains method determines weather a sequence contains a specified element by using the default equality comparer. The following code illustrated a how “contains” and “not contains” operations can be implemented to filter a list of objects. In this sample code we filter the objects on the “name” property, the code for generating the collection class can be obtained from my previous post:

//Filter by "007" containing as a part of the employee list
var sortedEmployees = EmployeeList.Where(i =>"007")).ToList();

//Filter by "007" NOT containing as a part of the employee list
sortedEmployees = EmployeeList.Where(i => !"007")).ToList();

The contains method also has an overloaded method, which can take a custom comparer as an argument. The custom comparer could be used to determine if an object is contained in a given sequence of objects. A sample implementation can be found at this location. My take away from the sample at MSDN is the implementation of the object comparer and more specifically the way the GetHashCode method has been implemented.

1. MSDN Online

Written by cavemansblog

January 10, 2012 at 12:48 am

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: