Gerhard Powell
Gerhard Powell

Reputation: 6175

Checking for item in Generic List before using it

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 == ...)
    ....
}

Upvotes: 5

Views: 754

Answers (3)

Saeed Amiri
Saeed Amiri

Reputation: 22555

You can do it simply with linq, just add using System.Linq in top of your namespace;

First if you want to get all results:

var items = list.Where(item=>item.Id == giveID).ToList();

Or if you just want first result;

var result = list.FirstOrDefault(item=>item.ID == givenID);

instead of item.Id == givenID you can put your own criteria. for example if item is string you can do item == "Test" or if is int do item == 5, ...

Upvotes: 3

Haris Hasan
Haris Hasan

Reputation: 30097

item = list.Find(item => item == ...);
if(null != item)
{
   //do whatever you want
}

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1500515

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.

Upvotes: 5

Related Questions