I have the following code:
var thing = (from t in things
where t.Type == 1 && t.IsActive
select t).SingleOrDefault();
if (thing == null)
{
// throw exception
}
things is a collection of Entity Framework Self-Tracking Entities
This works nicely, however I want to use a Lambda expression instead and changed the LINQ to this:
var thing = things.Select(t => t.Type == 1 && t.IsActive).SingleOrDefault();
Now Resharper is telling me Expression is always false for (thing == null).
What have I missed?
You want:
Selectperforms a projection (converting the type of the IEnumerable fromIEnumerable<Thing>toIEnumerable<bool>with valuestrueift.Type == 1 && t.IsActive == true, otherwisefalse), then theSingleOrDefaultreturns either the onlyboolin this sequence, or the default value of aboolwhich isfalseif the sequence is empty. This can never be null sinceboolis not a reference type.Whereperforms a filtering action (pulling out only those objects that meet a given criterion – in this case only selecting those whereTypeis1andIsActiveistrue), leaving the type of the IEnumerable asIEnumerable<Thing>. AssumingThingis a class, theSingleOrDefaultwill return the only item in the sequence ornull.In either case,
SingleOrDefaultwill throw an exception if the sequence contains more than one item (which is far more likely in theSelectversion!).