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?
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 .
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();
Do you find this approach better?
var lightestVehicle = listVehicles.OrderBy(x => x.Type).ThenBy(n => n.weight).Select(x => x).FirstOrDefault();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With