Here I have a simple example to find an item in a list of strings. Normally I use a for loop or anonymous delegate to do it like this:
int GetItemIndex(string search)
{
int found = -1;
if ( _list != null )
{
foreach (string item in _list) // _list is an instance of List<string>
{
found++;
if ( string.Equals(search, item) )
{
break;
}
}
/* Use an anonymous delegate
string foundItem = _list.Find( delegate(string item) {
found++;
return string.Equals(search, item);
});
*/
}
return found;
}
LINQ is new for me. Can I use LINQ to find an item in the list? If it is possible, how?
If you want the index of the element, this will do it:
You can’t get rid of the lambda in the first pass.
Note that this will throw if the item doesn’t exist. This solves the problem by resorting to nullable ints:
If you want the item:
If you want to count the number of items that match:
If you want all the items that match:
And don’t forget to check the list for
nullin any of these cases.Or use
(list ?? Enumerable.Empty<string>())instead oflist.