Selecting the first member of a group from LINQ search results

I have a set of vehicles in C #, and some cars are cars, and others are SUVs. I am wondering what is the best way to get the car with the lowest weight. If there is no car in the array, find the SUV with the lowest weight.
Below is the code segment I have LINQ. I am wondering if there is a better way to get 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 thing with groupby or another LINQ trick?

+5
source share
3 answers

You can order a type, put cars in front of SUVs, and then order by weight. This allows you to choose 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(); 
+3
source

Try the following:

  var lighttestvehicle = (from v in vehicles orderby v.Weight, v.Type ascending select v) .FirstOrDefault(); 
0
source

Do you find this approach better?

 var lightestVehicle = listVehicles.OrderBy(x => x.Type).ThenBy(n => n.weight).Select(x => x).FirstOrDefault(); 
0
source

Source: https://habr.com/ru/post/1276147/


All Articles