Searching Collections with Linq

In New Methods for Old Classes in C# I described how to create C# Extension Methods. As a practical matter, you will probably get much more use from some Extension Methods that are already ready and waiting – the methods of the System.Linq namespace.

The System.Linq methods support a wide variety of functions: filter, search, aggregation, and so on. They work “out of the box” on C# arrays, Lists, and other collections – any extension of IEnumerable.

Assume we are working with a very simple class, Person:

public class Person
    public string Name { get; set; }
    public int    Age { get; set; }
    public int    Weight { get; set; }

If we had an array of Person instances and wanted to retrieve the instance with Name value “Sam”, the legacy approach would be to use a for-loop:

Person[] people = {p1, p2, ...};
Person namedSam = null;
foreach (Person p :  people)
    if (p.Name == "Sam")
        namedSam = p;

But if our program uses namespace System.Linq, we could achieve the same with the following:

Person[] people = {p1, p2, ...};
Person namedSam = people.Where(p => p.Name == "Sam").FirstOrDefault();

(Note: through the magic IEnumerable, the list search terminates as soon as the first “Sam” is found, if any.  See IEnumerable is Lazy for an explanation.)

The System.Linq approach certainly has a lot less clutter, many fewer chances to mess up, and is performant to boot.

To unpack what’s going on: Where is an Extension Method.  It returns an IEnumerable instance that meets conditions specified by its arguments.

The Where method takes a Boolean lambda expression as its argument.  The variable p is the type of the elements of the collection to which Where is applied, which in this case is Person.  It’s almost as though the expression ranges over all the elements of the people array to choose those with Name “Sam”, except that as parenthetically noted above, the result collection is populated on demand.

The method FirstOrDefault selects the first Person instance from the result collection of people named Sam.  The “Default” qualifier means that that if no instance of Person matches the Where criteria, then the type’s default value is returned. For class Person, that would be null.

My GitHub project, SimpleLinqExample, is a C# project that illustrates basic list and array searching with System.Linq.

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