Collection searching using C# and LINQ

muyiwa profile image Muyiwa Olu Originally published at muyiwa.me on ・2 min read

Whenever I write C# code, one of the consistent actions I have to perform is searching a collection to obtain an element I want. For example: names.Where n => n == “Joe” will give me a collection representing all strings within the name collection that equal Joe. This is pretty straightforward, however what if the search parameter isn’t a string, like above, but a collection of strings?

Lets take a look at this with an example:

IEnumerable<string> names = new List<string> { "Joe", "Josh", "Mark", "Steve" };
IEnumerable<string> namesToSearch = new List<string> { "Joe", "Mark" };

The first variable, names, represents a collection - in this case a list of strings - with names. The second variable, namestoSearch is also a collection - a list of strings the represents names we want to find.

Our task is to find the strings in the names collection that match the strings in the namesToSearch collection.

There are several ways to do this, but my personal favourite is the following:

IEnumerable<string> searchResult = names.Where(n => namesToSearch.Any(nts => nts == n)); 

// Result: "Joe", "Mark"

This essentially gives us a subset of names for the values in namesToSearch.

As you can imagine, this is very useful — particularly when you are dealing with objects. If, instead of a list of names, we had a list of Person objects and each Person had a name, we could still perfom the above by accessing the property, for example:

IEnumerable<Person> people = new List<Person> {
    new Person { Name = "Joe" },
    new Person { Name = "Josh" },
    new Person { Name = "Mark" },
    new Person { Name = "Steve" }

IEnumerable<Person> peopleSearchResult = people.Where(p => namesToSearch.Any(nts => nts == p.Name)); 

// Result: "Person {"name" : "Joe"}, Person {"name" : "Mark"}"

And don’t forget — since this is LINQ, you can still chain the commands — so if you didn’t want a collection of Person objects, but just the names instead, you could do:

IEnumerable<string> peopleSearchResultAsNames = peopleSearchResult.Select(p => p.Name);

// Result: "Joe", "Mark"

Pretty cool, huh?!

Posted on by:

muyiwa profile

Muyiwa Olu


Technology geek, curious human, and fan of the Oxford comma.


markdown guide