Example 1: (Exists) Returns true if the list contains items 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}; bool result = list.Exists(x => x == 500); Console.WriteLine(result); Console.ReadLine(); } } |
Output:
1 2 3 | True |
Example 2: (Exists) Returns false if the list doesn’t contain items 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}; bool result = list.Exists(x => x > 500); Console.WriteLine(result); Console.ReadLine(); } } |
Output:
1 2 3 | True |
Example 3: (Find) Here we consider the Find() method on List. Find accepts a Predicate, which we can specify as a lambda expression. It returns the first match.
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(item => item > 180); Console.WriteLine(result); Console.ReadLine(); } } |
Output:
1 2 3 | 200 |
Example 4: (FindLast) To search backwards, use the FindLast method. FindLast will scan the List from the last element to the first. Here we use FindLast instead of Find.
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.FindLast(item => item > 180); Console.WriteLine(result); Console.ReadLine(); } } |
Output:
1 2 3 | 700 |
Example 5: (FindIndex) FindIndex returns the index of the first matching element, starting its search from the first element.
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.FindIndex(element => element >= 280); Console.WriteLine(result); Console.ReadLine(); } } |