Linq在C#中的排名 [英] Linq List Ranking in C#

查看:424
本文介绍了Linq在C#中的排名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的列表,其中包含名称和分数列表.我从使用linq来获得人物列表的总分中得到的分数:

I have the below list which consist of a list of names and scores. The scores I got from using linq to get the sum of points for the list of peope:

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

所以我能够对列表进行分组并得出总和,但是现在我试图根据得分对它们进行排名.因此,我尝试获取以下列表:

So i was able to group the list and make the sums, but now I am trying to rank these based on the score. So I am trying to get the below list:

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

但是我正在使用的linq代码似乎并没有为我找到合适的排名.

But the linq code I am using doesn't seem to be getting the right ranks for me.

这是我的代码,用于创建列表,求和与排名:

Here's my code for making the list and making the sums and ranking:

    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中包括正确的排名.

I just would like to know how to include correct ranks in linq.

推荐答案

您必须OrderByDescending groupedData(具有总分),而不是包含未汇总的单个得分的原始数据.

You have to OrderByDescending the groupedData (which has a total score) rather than the raw data containing non-summed, individual scores.

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

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

Edit: (putting the correct rank into 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));

这篇关于Linq在C#中的排名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆