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.

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 List.Contains[int item]

If 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 List nums = new List[]; nums.Add[52]; nums.Add[68]; nums.Add[73]; //check if element is present in the list bool isElementPresent = nums.Contains[68]; Console.WriteLine["68 present in the list : "+isElementPresent]; //check if element is present in the list isElementPresent = nums.Contains[59]; Console.WriteLine["59 present in the list : "+isElementPresent]; } }

Run the above C# program.

Output

68 present in the list : True 59 present in the list : False

Example 2 – Check if Object is present in the C# List

In 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 List cars = new List[]; //add objects to the list cars.Add[new Car["Toyota", 1250000]]; cars.Add[new Car["Tata", 1300000]]; cars.Add[new Car["Honda", 1150000]]; //create a car object Car mycar = new Car["Tata", 1300000]; // check if mycar is present in the list bool isCarPresent = cars.Contains[mycar]; Console.WriteLine[isCarPresent]; } } class Car{ public string name; public int price; public Car[string name, int price]{ this.name = name; this.price = price; } }

Run the C# program.

Output

False

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 List cars = new List[]; //add objects to the list Car car1 = new Car["Toyota", 1250000]; cars.Add[car1]; Car car2 = new Car["Tata", 1300000]; cars.Add[car2]; Car car3 = new Car["Honda", 1150000]; cars.Add[car3]; // check if car2 is present in the list bool isCarPresent = cars.Contains[car2]; Console.WriteLine[isCarPresent]; } } class Car{ public string name; public int price; public Car[string name, int price]{ this.name = name; this.price = price; } }

Run the above C# program.

True

In 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.

Conclusion

In 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:

  1. Use the Contains method to check if the item exists in the list. It returns true if the item exists in the list.
  2. If Contains is true, use the Add method to add the item to the list.
  3. Create a generic extension method to make it easy to add an item to the list if it doesn't exist.

List list = new List[] { "exists" }; list.AddIfNotExists["exists"]; list.AddIfNotExists["doesn't exist"]; Console.WriteLine[string.Join[", ", list]]; public static bool AddIfNotExists[this List list, T value] { if [!list.Contains[value]] { list.Add[value]; return true; } return false; }

Performance

The 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:

  • Use a hashset or a dictionary,
  • BinarySearch method on the List
  • Sorted List

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.

IEnumerable

To implement the "add if not exists" method using IEnumerable:

  1. Use Contains on the IEnumerable to check if the item exists in the list.
  2. If Contains is false, use Append on the IEnumerable to add the item.
  3. Use a new variable to store the returned value because Append creates a new collection.

public static IEnumerable AddIfNotExists[this IEnumerable 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 newWords = words.AddIfNotExists["celery"] .AddIfNotExists["apple"] .AddIfNotExists["banana"]; Console.WriteLine[string.Join[", ", newWords]];

HashSet

Consider 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 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.

Video liên quan

Chủ Đề