Home > OS >  How to rank elements when it has duplicates
How to rank elements when it has duplicates

Time:09-10

I am trying to figure out a way to rank items in a list that has duplicated values.

For example:

QTECDE RANK
40 1
30 2
24 3
18 4
4 5
4 5
3 6

But my code always skips a number when I have a duplicated rank. This what I get:

QTECDE RANK
40 1
30 2
24 3
18 4
4 5
4 5
3 7 (7 insted of 6)

Here's my code:

var rankedList = oList.OrderByDescending(p => p.QTECDE)
                      .Select((p, i) => new { Order = 1   i, lst = p })
                      .GroupBy(p => new { p.lst.QTECDE })
                      .SelectMany(g => g.Select(p => new
                                        {
                                         RANK = g.Min(x => x.Order),
                                         NO_ART = p.lst.NO_ART,
                                         QTECDE = p.lst.QTECDE,
                                         LIB_INDEX_FR_SUP = p.lst.LIB_NIVEAU_SUP_FR,
                                         LIB_IMAGE = p.LIB_IMAGE,
                                        }));

Any solutions?

CodePudding user response:

You just need the index of the group not the items:

var rankedList = oList
    .OrderByDescending(p => p.QTECDE)
    .GroupBy(p => new { p.QTECDE })
    .SelectMany((g, groupIndex) => g
        .Select(p => new
        {
            RANK = groupIndex   1,
            NO_ART = p.NO_ART,
            QTECDE = p.QTECDE,
            LIB_INDEX_FR_SUP = p.LIB_NIVEAU_SUP_FR,
            LIB_IMAGE = p.LIB_IMAGE,
        }));

CodePudding user response:

You're determining the rank/order on your source items. You want to apply the (item, index) to your SelectMany() instead of your Select().

  • Related