简体   繁体   English

如何在C#上对具有多个条件的列表进行排名

[英]How to rank a list with multiple conditions on c#

I am trying to figure out how to rank a list with multiple conditions: 我试图弄清楚如何对具有多个条件的列表进行排名:

  1. This is my list: 这是我的清单:

Excel列表

  1. Let me explain the list above: 让我解释一下上面的列表:

a. 一种。 ' AreaCode ' is an unique ID for each group of the list. 对于每个列表组,“ AreaCode ”是唯一的ID。

b. b。 I will rank the list based on highest value of Rank 1 (highlighted with yellow). 我将根据等级1的最高值对列表进行排名(以黄色突出显示)。

c. C。 If Rank 1 has same value, I will find highest value of Rank 2 (highlighted by green). 如果等级1具有相同的值,我将找到等级2的最高值(以绿色突出显示)。

d. d。 If Rank 2 has same value, I will find highest value of Rank 3 (highlighted by blue). 如果等级2具有相同的值,我将找到等级3的最高值(蓝色突出显示)。

e. e。 In this case, there are same value for Rank 1 (7 and 7), so I will find the highest value for Rank 2, however the Rank 2 value also same (4 and 4), so I will find the highest value for Rank 3 (1 and 2). 在这种情况下,等级1的值相同(7和7),因此我将找到等级2的最大值,但是等级2的值也相同(4​​和4),因此我将找到等级的最大值3(1和2)。

f. F。 So ' Ranking ' column is the result that I want to achieve, which is a list with these value: 因此,“ 排名 ”列是我想要实现的结果,它是具有以下值的列表:
[1, 1, 1, 3, 3, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 3, 3, 3] . [1、1、1、3、3、3、2、2、2、2、2、2、1、1、1、3、3、3]

  1. Last time I can do but with simple scenario (there are no Rank 1, Rank 2 or Rank 3) using this code: 上次我可以这样做,但是使用简单的场景(没有等级1,等级2或等级3),使用此代码:

     var rankings = myIndexList.GroupBy(x => x) .OrderByDescending(g => g.Key) .Select((g, i) => new { Key = g.Key, Rank = i + 1 }) .ToDictionary(x => x.Key, x => x.Rank); var output = myIndexList.Select(x => new { Col1 = x, Rank = rankings[x] }) .ToList(); 

Any ideas to achieve the result on ' Ranking ' column? 有什么想法可以在“ 排名 ”列上取得结果吗?

Thank You! 谢谢!

I recommend this. 我推荐这个。

public class Item
{
    public string Name { get; set; }
    public int Value { get; set; }
}

/////
var list = new List<(Item Col1, int Rank)>();

var nameGroup = items.GroupBy(i => i.Name);
var sorted = nameGroup.OrderBy(i => i.Key);

foreach (var group in sorted)
{
    int ranking = 1;
    foreach (var item in group.OrderByDescending(i => i.Value))
    {
        list.Add((Col1: item, Rank: ranking++));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM