簡體   English   中英

C# 集合 select 屬性的值與另一個屬性的最小值

[英]C# Collection select value of the property with minimum value of another property

所以假設我有一個類型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);

使用MinBy

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

怎么樣:

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

當然,您可以擁有幾輛具有相同最低速度的汽車,因此您可以得到 IEnumerable。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM