[英]C# LINQ select hierarchy from list where root has a certain property value
[英]C# take x items from list where each one has a unique value for a certain property
如果我有一个像这样的对象数组
public class Expert
{
public string Id { get; set; }
public int Rating { get; set; }
public decimal Price { get; set; }
public string Availability { get; set; }
}
其中 rating 可以是以下任何一项:[1,2,3,4,5]
我想从列表中检索 5 个项目,其中每个项目都有不同的评级。
所以我想最终得到一个包含 5 个项目的列表,其中 1 的评分为 1,另一个评分为 2,依此类推,最高为 5。
您可以只使用GroupBy
然后使用Select
投影First
结果
var result = list.GroupBy(x => x.Rating)
.Select(x => x.First());
或者正如@Enigmativity 在评论中提到的那样,它提供了一定程度的灵活性
var result = list.GroupBy(x => x.Rating)
.SelectMany(x => x.Take(1));
进一步阅读
对序列的元素进行分组。
将序列的每个元素投影到新形式中。
返回序列的第一个元素。
一个可能的解决方案是按等级分组,然后选择每个组的第一个元素。 简单可行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.