C# Collection select value of the property with mi

2019-02-19 08:29发布

问题:

So let's say I have a type Car with two properties Speed and Color

public class Car
{
   public int Speed {get; set;}
   public string Color {get; set;}
}

Using LINQ I may find the minimum speed

int minSpeed = collection.Min(em => em.Speed);

so minSpeed will contain the value of speed of the car with the minimum speed in collection.

But how can I do something similar to get the color of the car?

Something like:

string color = collection.Min(em => em.Speed).Select(x => x.Color);

回答1:

Use MinBy.

Car slowestCar = collection.MinBy(em => em.Speed);
string color = slowestCar.Color;


回答2:

How about:

IEnumerable<string> color = collection.Where(x=> x.Speed == collection.Min(em => em.Speed)).Select(x => x.Color).Distinct();

Of course, you can have several cars with same minimum speed, so you get IEnumerable.



标签: c# linq .net-4.0