Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to find if a value exists within a C# List [duplicate]

Tags:

c#

list

In C# if I have a List of type bool. What is the fastest way to determine if the list contains a true value? I don’t need to know how many or where the true value is. I just need to know if one exists. I will be searching many extremely large lists.

like image 921
Aaron Benzel Avatar asked Apr 17 '13 11:04

Aaron Benzel


6 Answers

Just use bool trueInList = list.Contains(true);. This loops the list until there's a true.

Why do you need something faster with such a simple use-case?

like image 143
Tim Schmelter Avatar answered Oct 27 '22 00:10

Tim Schmelter


Use either list.Contains(true) or list.Any(true). For a normal list both have complexity O(n). Since Any() is an extension method though, which needs to invoke delegates, the Contains() might still be a bit faster. But to be sure I would simply test both with a large collection.

like image 38
treze Avatar answered Oct 27 '22 02:10

treze


You could use Any().

list.Any(b => b);
like image 22
user707727 Avatar answered Oct 27 '22 02:10

user707727


Try this:

var result = myBoolList.Any(i => i==true);
like image 42
Hossein Narimani Rad Avatar answered Oct 27 '22 01:10

Hossein Narimani Rad


You use the Any(...)

list.Any(c => c == true);

or just

list.Any(c => c);
like image 32
Jens Kloster Avatar answered Oct 27 '22 02:10

Jens Kloster


You can use BinarySearch method of the list.

if(list.BinarySearch(true) > 0){...}
like image 25
Saeed Avatar answered Oct 27 '22 00:10

Saeed