I have a simple one-line linq query to find items in a list which contain the highest property value, and create a new list with them only if there are a certain count of items that match this criteria. For example:
List<MyObject> objects = new List<MyObject>()
{
new MyObject() { MyValue = 6 },
new MyObject() { MyValue = 7 },
new MyObject() { MyValue = 7 },
new MyObject() { MyValue = 8 },
new MyObject() { MyValue = 8 },
};
int countRequired = 2;
List<MyObject> highestValue2Required = objects.GroupBy( o => o.MyValue )
.OrderByDescending( g => g.Key )
.Where( g => g.Count() == countRequired )
.FirstOrDefault()
.ToList();
Providing there is data in my list that sattisfies these conditions, a new list will be created containing two instances of MyObject
, the ones where MyValue = 8
.
However, if there is no data matching the criteria, I hit an exception because the IGrouping
result from the query is null, and calling ToList()
on this doesnt work. For example:
int countRequired = 3;
List<MyObject> highestValue3Required = objects.GroupBy( o => o.MyValue )
.OrderByDescending( g => g.Key )
.Where( g => g.Count() == countRequired )
.FirstOrDefault()
.ToList();
Because there are only two instances of MyObject
in the list where MyValue
equals the highest value (which is 8), the query throws an exception
System.ArgumentNullException: 'Value cannot be null.
Is it possible to this null value in order to return an empty list within my "one line" query?
The obvious way to do this would be to remove the ToList()
call and simply return an IGrouping
result, and only call ToList()
when it's not null, but I'm curious as to whether it can be done inline.