C#: LINQ – Filtering by Custom Extension

Please see my other LINQ articles.

Extending LINQ to perform custom searches

In this article, I’ll demonstrate how to create a custom extension in LINQ which may be used to extend searching capability on collections.

In my C#: Json – Populate objects from a file I demonstrated how to read objects from a file.

Now, I’ll update the method used to read Person objects to also filter by name.

First, I’ll create the following class in which to add my new ByName() method.

Note: The return type is IEnumberable because this is the interface all LINQ queries return. Also, for custom extensions the first parameter must use this keyword to specify against which type ByName() may be applied.

With ByName() ready for use, I’ll now extend my previous GetPeopleFromFile() method. Previously it returned two records.

Now that I’m calling ByName() and passing “paul,” only that object will be returned.

.NET Fiddle: https://dotnetfiddle.net/r3NO37