Using delegates you can pass a lambda expression as a parameter to a function, and then use it in LINQ queries. This can be done with Func<…> delegates.
If you want to pass a lambda expression to be used, for example, in Where clause, you need a Func<T, bool> delegate. Just hover the mouse over Where in your code, and IntelliSense would show you the required syntax.
Here is a simple demo program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
using System; using System.Collections.Generic; using System.Linq; namespace ConsoleApplication1 { class Program { class Item { public int Id { get; set; } public string Name { get; set; } } static void Main(string[] args) { List<Item> items = new List<Item> { new Item(){ Id = 1, Name = "Adam" }, new Item(){ Id = 2, Name = "Billy" }, new Item(){ Id = 3, Name = "Cecil" } }; Console.WriteLine("Length == 5"); PrintItems(items, x => x.Name.Length == 5); Console.WriteLine("Id is odd number"); PrintItems(items, r => r.Id % 2 == 1); } static void PrintItems(List<Item> list, Func<Item, bool> condition) { var selectedItems = list.Where(condition); foreach (var item in selectedItems) { Console.WriteLine("{0}, {1}", item.Id, item.Name); } } } } |