Check if item exists in list c#
C# Check if Element is present in ListList is a collection of items/elements. You can check if the list contains an item or an object is present in the list. Show In this tutorial, we shall learn how to check if an item/element is present in a given List. To check if an element is present in the list, use List.Contains() method. The definition of List.Contains() method is given below. bool ListIf given element is present in the list, then List.Contains() returns True, else, it returns False. Example 1 Check if Element is in C# List using Contains()In the following program, we have a list of integers. We shall check if element 68 is present in the list or not using Contains() method. As 68 is present in the list, List.Contains() method returns True. Then we shall check if the element 59 is present in the list. As 59 is not present in the list, List.Contains() method returns false. Program.cs using System; using System.Collections.Generic; class Program { static void Main(string[] args) { //create list ListRun the above C# program. Output Example 2 Check if Object is present in the C# ListIn this example, we shall check if a given object is present in the list. When working with objects, List.Contains() method considers that two objects are equal only if they refer to same object instance. Two instances with same values for its properties is not considered equal. Program.cs using System; using System.Collections.Generic; class Program { static void Main(string[] args) { //create list ListRun the C# program. Output The values for properties are same, but the object instance is not the same. Let us rewrite the above program and modify as shown below. Program.cs using System; using System.Collections.Generic; class Program { static void Main(string[] args) { //create list ListRun the above C# program. TrueIn the above program, we have used the same instance, that we added to the list, to check with Contains() method. So, Contains() method, when comparing the objects in the list, finds a match for the given object. ConclusionIn this C# Tutorial, we learned how to check if an element or object is present in the list or not using List.Contains() method. |