Check if item in list c#
List 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 68 present in the list : True 59 present in the list : FalseExample 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 FalseThe 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. To add an item to the list, if it doesn't exist:
List<string> list = new List<string>() { "exists" }; list.AddIfNotExists("exists"); list.AddIfNotExists("doesn't exist"); Console.WriteLine(string.Join(", ", list)); public static bool AddIfNotExists<T>(this List<T> list, T value) { if (!list.Contains(value)) { list.Add(value); return true; } return false; } PerformanceThe Contains method does a linear, O(n) search. If you have a lot of items in the list, this can be slow. To get a faster collection search, consider to:
In most cases, you won't run into performance problems. If you have a list with over 10,000 items, do some performance testing to find which method performs the best. IEnumerableTo implement the "add if not exists" method using IEnumerable:
public static IEnumerable<T> AddIfNotExists<T>(this IEnumerable<T> list, T value) { if (!list.Contains(value)) { return list.Append(value); } return list; } We need to create a new variable because in C#, IEnumerable is an immutable collection. It means that we cannot add, modify, or remove items. The Append method does not change the elements in the collection, it just makes a copy of the collection with the extra element added. The benefit of using the IEnumerable interface is that it's more general. The code will work with any type that implements IEnumerable, not just List. For example, we could use the same code to add an item to a string list: string[] words = { "apple", "banana", "carrot" }; IEnumerable<string> newWords = words.AddIfNotExists("celery") .AddIfNotExists("apple") .AddIfNotExists("banana"); Console.WriteLine(string.Join(", ", newWords)); HashSetConsider using a HashSet to prevent duplicate values in a collection. In C#, HashSet cannot have duplicate elements. The implementation takes care of it for you. So, if you keep calling the Add method with an existing item, nothing will happen: HashSet<string> items = new (); items.Add("1"); items.Add("1"); items.Add("1"); items.Add("2"); Console.WriteLine(string.Join(", ", items)); However, unlike List, HashSet doesn't guarantee order of items. |