C# Collection select value of the property with minimum value of another property

我的未来我决定 提交于 2019-12-19 10:15:37

问题


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.



来源:https://stackoverflow.com/questions/6725781/c-sharp-collection-select-value-of-the-property-with-minimum-value-of-another-pr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!