Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for item in Generic List before using it

Tags:

c#

list

linq

With a generic List, what is the quickest way to check if an item with a certain condition exists, and if it exist, select it, without searching twice through the list:

For Example:

if (list.Exists(item => item == ...))
{
    item = list.Find(item => item == ...)
    ....
}
like image 302
Gerhard Powell Avatar asked Oct 25 '11 19:10

Gerhard Powell


2 Answers

Either use Find once and compare the result with default(T), or if default(T) could be the item itself, use FindIndex and check whether the index is -1:

int index = list.FindIndex(x => x...);
if (index != -1)
{
    var item = list[index];
    // ...
}

If you're using .NET 3.5 or higher, it's more idiomatic to use LINQ - again, if default(T) isn't a problem, you could use something like:

var item = list.FirstOrDefault(x => x....);
if (item != null)
{
    ...
}

Using LINQ will let you change from List<T> to other collections later on without changing your code.

like image 65
Jon Skeet Avatar answered Sep 23 '22 22:09

Jon Skeet


item = list.Find(item => item == ...);
if(null != item)
{
   //do whatever you want
}
like image 30
Haris Hasan Avatar answered Sep 26 '22 22:09

Haris Hasan