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
Findonce and compare the result withdefault(T), or ifdefault(T)could be the item itself, useFindIndexand check whether the index is -1: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:Using LINQ will let you change from
List<T>to other collections later on without changing your code.