LINQ extension methods take predicates to filter the list by. Where
, First
, FirstOrDefault
, Single
, SingleOrDefault
(to name but a few) all take the same predicate.
Some Lambda expression to filter the list by.
public class MyClass
{
public int Id {get;set;}
public int Other {get;set;}
}
// myClasses is a populated list <-- this needs to be checked.
var result = myClasses.FirstOrDefault(x => x.Id == specificId && x.Other == specificOther);
Result
should now contain either a single MyClass
instance or a null
.
If you omit the OrDefault()
then your code will throw an error if it can't find an Instance that matches the predicate.
If the predicate returns several items, then First
will pick the first item. If you swap First
to Single
and the predicate returns several items, it will throw an exception.
Things to check
The list you are performing the query against has a list of instances.
The variables specificId
and specificOther
have values that exist in the list. The last thing you want to do is be wondering why it isn't returning anything, when actually it is doing exactly what you asked for and that the reason for failing is the values you were using to query with where wrong.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…