Example 1: Returns the first occurrence of item matching the specified predicate.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var list = new List<int> { 100,200,300,400,500,600,700}; int result = list.Find(x => x > 200); Console.WriteLine(result); Console.ReadLine(); } } |
Output:
1 2 3 |
300 |
Example 2: Returns list with items matching the specified predicate.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var listA = new List<int> { 100,200,300,400,500,600,700}; var listB = listA.FindAll(x => x > 200); Console.WriteLine(listB.Count); Console.ReadLine(); } } |
Output:
1 2 3 |
5 |
Example 3: We examine the Exists method on List. Exists returns whether a List element is present. We invoke this method with a lambda expression.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { var listA = new List<int> { 100,200,300,400,500,600,700}; bool exists = listA.Exists(element => element > 600); Console.WriteLine(exists); Console.ReadLine(); } } |
Output: True