Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# best approach to check a value is exist in a List Several times

Tags:

c#

search

I have list of integers and I want to know a value exist in my list Several times.

What is the best approach to do this?

catching data using LookUp or dictionary or HashMap or ...?

Example:

List<int> samples = {5,4,6,2,1}
// if(2 exist in samples) do something ...
// if(3 exist in samples) do something ...
// if(5 exist in samples) do something ...
// if(8 exist in samples) do something ...
// if(13 exist in samples) do something ...
// if ....
like image 447
Amir133 Avatar asked Jan 28 '26 07:01

Amir133


1 Answers

You can store them in HashSet and check whether value exists with O(1):

var unique = new HashSet<int>(){ 5,4,6,2,1};
var hasValue = unique.Contains(1);

and then just check:

if (unique.Contains(2)) 
    // do something ...

In addition, HashSet<T> prevents storing duplicates, so it is extremely fast.

UPDATE:

List<T> will search with O(N). Why? Because Big O Notation should consider the worst case of time complexity. Let's imagine we have the following list:

var numbers = new List<int> { 5, 4, 6, 2, 1 };

and we want to find number 1. So Contains() method of List<T> has to iterate the whole array until it finds number 1. So we have O(N).

LinkedList<T> will search with O(N). Why? The reason is the same like in List<T>. However, LinkedList<T> does not have an array under the hood, it has a class which has a pointer to next element and next element has pointer to the next element and so on. We have to iterate all elements to find an item.

HashSet<T> will search with O(1). Why? The reason is HashSet<T> under the hood will not iterate through array. It will run internal method InternalGetHashCode which returns position of number in array. You can see the source code here.

In addition, there is a very nice answer about How can hashset.contains be O(1) with this implementation?

like image 62
StepUp Avatar answered Jan 29 '26 20:01

StepUp