c# - C# 中的 Linq 列表排名

标签 c# linq observablecollection

我有以下列表,其中包含名称和分数列表。我使用 linq 获取人员列表的分数总和得到的分数:

  Name  Score
   Ed    5
   John  6
   Sara  7
   Dean  3
   Nora  4

所以我能够对列表进行分组并计算总和,但现在我试图根据分数对它们进行排名。所以我正在尝试获取以下列表:

Rank Name Score
 1   Sara  7
 2   John  6
 3   Ed    5
 4   Nora  4
 5   Dean  3

但是我使用的 linq 代码似乎没有为我获得正确的排名。

这是我制作列表、计算总和和排名的代码:

    public class Person
    {

        public int Rank { get; set; }
        public string Name { get; private set; }
        public int Score { get; set; }

        public Person(int rank, string name, int score)
        {
            Rank = rank;
            Name = name;
            Score = score;

        }
    }

    public ObservableCollection<Person> Persons { get; set; }
    public MainWindow()
    {            
 Persons = new ObservableCollection<Person>();
        var data = lines.Select(line => {
        var column = line.Split(',');
        var name = column[0];
        int score = int.Parse(column[1]);
        int rank =0; 
        return new { name, score, rank };
    });

        var groupedData = data.OrderByDescending(x => x.score).GroupBy(p => p.name).Select((g, i) => new { name = g.Key, rank=i+1, score = g.Sum(p => p.score)});

    var persons = groupedData.Select(p => new Person(p.rank, p.name, p.score));

    foreach (var person in persons) {
        Persons.Add(person);
    }
    datagrid.ItemsSource = Persons;
}

我只是想知道如何在 linq 中包含正确的排名。

最佳答案

您必须OrderByDescending groupedData(它有一个总分)而不是包含非总分的原始数据。

var persons = groupedData.Select(p => new Person(p.rank, p.name, p.score)).OrderByDescending(x => x.Score);

编辑:(将正确的排名放入 Person.Rank)

var groupedData = data.GroupBy(p => p.name).Select(g => new { name = g.Key, score = g.Sum(p => p.score)}).OrderByDescending(x => x.score);
var persons = groupedData.Select((p,i) => new Person(i+1, p.name, p.score));

关于c# - C# 中的 Linq 列表排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45838787/

相关文章:

c# - 将存储过程转换为 LINQ 查询

c# - 过滤某种类型的 ObservableCollection<Object> 对象

c# - 在 MySQL 中获取多个 LastInserted ID?

C#:使用私有(private)静态成员进行单元测试?

c# - 在 Debug模式下未获取 DotNetCore 授权策略

c# - Entity Framework 过滤器嵌套集合

asp.net-mvc - Entity Framework 不将值插入可为空的日期时间字段

wcf - 在 Silverlight 中绑定(bind)来自 WCF 的对象集合的好模式是什么?

c# - 合适的 ObservableCollection

c# - 使用户能够从另一个进程中选择控件/窗口