Filter an array of integers with LINQ C# using a lambda expression
January 22, 2014 4 Comments
Consider the following array of integers:
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Say you want to filter out the odd numbers. One way to achieve this is using LINQ with a lambda expression. You’ll need a delegate that returns a boolean:
public delegate bool IntegerFilter(int i);
The following function accepts an integer array and a delegate and returns the filtered array:
public int[] FilterIntegerArray(int[] ints, IntegerFilter filter) { List<int> intList = new List<int>; foreach (int i in ints) { if (filter(i)) { intList.Add(i); } } return intList.ToArray(); }
You can call this method as follows using lambda expression that matches the signature of the delegate:
int[] oddNumbers = FilterIntegerArray(nums, i => ((i & 1) == 1) });
You can view all LINQ-related posts on this blog here.
How about just:
var oddNumbers = nums.Where(i => i % 2 == 1).ToList();
Jan, that certainly works and there are multiple ways to solve the problem. I just wanted to highlight the usage of delegates and lambdas.
//Andras
Okay, I think this is not a very good example for anything. First you should use yield return instead of building a new list, second Jan is right, that you can just use WHERE to solve the problem. You just made a very specialized version of a functionality that is already in C#.Just saying.
Rude..just saying..