C#从列表中获取x个项,其中每个项对于特定属性都有唯一的值

问题描述

如果我有这样的对象数组

public class Expert
{
    public string Id { get; set; }
    public int Rating { get; set; }
    public decimal Price { get; set; }
    public string Availability { get; set; }
}

其中评分可以是以下任意一项:[1,2,3,4,5]

我想从列表中检索5个项目,每个项目的评分都不同。

所以我想最后列出5个项目,其中1个为1,另一个为2,依此类推,直到5。

解决方法

您可以只使用GroupBy,然后用First投影Select结果

var result = list.GroupBy(x => x.Rating)
                 .Select(x => x.First());

或@Enigmativity在评论中提到的,它具有一定程度的灵活性

var result = list.GroupBy(x => x.Rating)
                 .SelectMany(x => x.Take(1));

进一步阅读

Enumerable.GroupBy Method

对序列的元素进行分组。

Enumerable.Select Method

将序列的每个元素投影为新形式。

Enumerable.First Method

返回序列的第一个元素。

,

可能的解决方案是按等级分组,然后选择每个分组的第一个元素。完全可行。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...