Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting first element of a group from LINQ search results

Tags:

I have an array of Vehicles in C# and some vehicles are Cars and others are SUVs. I am wondering what is the best way to fetch car with lowest weight. If no car is found in the array then find SUV with lowest weight.
Below is code segment I have using LINQ. I am wondering if there is better way to fetch this using one query instead of two queries.

Vehicle listVehicles[] = ...
Vehicle lightestVehicle = (from aVehicle in listVehicles
                      where aVehicle.Type == CAR
                      orderby aVehicle.Weight ascending)?.FirstOrDefault();
if (null == lightestVehicle)
    lightestVehicle = (from aVehicle in listVehicles
                      where aVehicle.Type == SUV
                      orderby aVehicle.Weight ascending)?.FirstOrDefault();
return lightestVehicle;

Is there a better way to accomplish the same using groupby or some other LINQ trick?

like image 340
videoguy Avatar asked Mar 29 '18 02:03

videoguy


People also ask

How do I get my first record in LINQ?

Solution 1int id = 2; var item = lstData. FirstOrDefault(k => k.ID == id); if (item != null) { // use the Item object to read the properties. // your code here... } if we are in doubt that duplicate records may contains, then we can go for FirstOrDefault .


2 Answers

You can order on the type, putting cars ahead of SUVs, and then order by weight. This lets you pick the lightest car if there are any cars, or the lightest SUV if there are no cars:

return listVehicles
    .Where(v => v.Type == CAR || v.Type == SUV)
    .OrderBy(v => v.Type == CAR ? 0 : 1)
    .ThenBy(v => v.Weight)
    .FirstOrDefault();
like image 73
Sergey Kalinichenko Avatar answered Nov 03 '22 22:11

Sergey Kalinichenko


Do you find this approach better?

var lightestVehicle = listVehicles.OrderBy(x => x.Type).ThenBy(n => n.weight).Select(x => x).FirstOrDefault();
like image 44
Kunal Khivensara Avatar answered Nov 03 '22 22:11

Kunal Khivensara