Filtering collections in C#

Jason Z picture Jason Z · Aug 25, 2008 · Viewed 285.1k times · Source

I am looking for a very fast way to filter down a collection in C#. I am currently using generic List<object> collections, but am open to using other structures if they perform better.

Currently, I am just creating a new List<object> and looping thru the original list. If the filtering criteria matches, I put a copy into the new list.

Is there a better way to do this? Is there a way to filter in place so there is no temporary list required?

Answer

Jorge C&#243;rdoba picture Jorge Córdoba · Aug 25, 2008

If you're using C# 3.0 you can use linq, way better and way more elegant:

List<int> myList = GetListOfIntsFromSomewhere();

// This will filter out the list of ints that are > than 7, Where returns an
// IEnumerable<T> so a call to ToList is required to convert back to a List<T>.
List<int> filteredList = myList.Where( x => x > 7).ToList();

If you can't find the .Where, that means you need to import using System.Linq; at the top of your file.