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 == ...)
....
}
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.
item = list.Find(item => item == ...);
if(null != item)
{
//do whatever you want
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With