videoguy
videoguy

Reputation: 1908

Selecting first element of a group from LINQ search results

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?

Upvotes: 5

Views: 347

Answers (3)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

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();

Upvotes: 3

Kunal Khivensara
Kunal Khivensara

Reputation: 1669

Do you find this approach better?

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

Upvotes: 1

Juan M. Vergara
Juan M. Vergara

Reputation: 196

Try this:

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

Upvotes: 0

Related Questions