Home > Development > Functional programming Filter Operator with LINQ

Functional programming Filter Operator with LINQ


One of the great things about LINQ is that it allows us to write declarative code without going into the intricate details of specifying how to filter items in a collection. This sort of programming has it roots in functional programming and thanks to people at Microsoft like Erik Meijer  this has been bought to .NET languages like C#. I would like to show you the functional programming function called Filter. Basically it letters you filter a collection based on a predicate and return a new collection with only items matching the criteria specificied. The Filter function in LINQ is called Where and is an extension method on IEnumerable<T>.

Here is an example.

public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine (“Linq Samples By Blair Davidson – Functional Filter Operator”);
List<Customer> customers = new List<Customer>{
new Customer{ Id = 1, Name = “Blair Davidson”},
new Customer{ Id = 2, Name = “Tim Davidson”},
new Customer{ Id = 3, Name = “Tom Davidson”},
new Customer{ Id = 4, Name = “Michelle Davidson”},
new Customer{ Id = 5, Name = “Sophie Davidson”},
new Customer{ Id = 6, Name = “Esther Hew”}
};
Array.ForEach(customers.Where( x => x.Name.Contains(“Davidson”)).ToArray(),
x => Console.WriteLine(x.Name));
}
}

The above code filter items that only contain the name Davidson and convert the results to an array an print the name of each item to the console. The great thing about this code is that you dont need horrible imperitive for loop to do this the Where extension method does this with the use of functional programming techniques.

The next functional high order function we will look at is the Map function and how it work with in LINQ.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: