C#Collection选择具有最小值的另一个属性的属性值

时间:2011-07-17 18:18:25

标签: c# linq .net-4.0

所以,假设我的类型Car有两个属性SpeedColor

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

使用LINQ我可能会找到最低速度

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

所以minSpeed将包含收集最低速度的汽车速度值。

但我怎么能做类似的事情来获得汽车的颜色呢?

类似的东西:

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

2 个答案:

答案 0 :(得分:4)

使用MinBy

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

答案 1 :(得分:0)

怎么样:

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

当然,你可以拥有几辆具有相同最低速度的汽车,因此你可以获得IEnumerable。