Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReIndex Number List but keep Duplicates in Order C#

Tags:

c#

linq

I'm trying to reorder a list that essentially gets rid of duplicates. Which I have been able to do. The part that is tripping me up is, if there are duplicates I want to keep them, and maintain the order

Examples -

Input = 1,3,3,4 Output = 1,2,2,3

Input = 1,3,5,6,6 Output = 1,2,3,4,4

Any help would be appreciated.

EDIT -

Code I've attempted.

for (int i = 1; i <= numList.Count; i++)
{
    if (numList[i - 1] == numList[i])
    {
        foreach (var item in numList.Where(x => x == numList[i - 1]))
        {
            testList.Add(item);
            i++;
        }
        foreach (var item in testList)
        {
            numList.Add(item);
        }

    }
    else
    {
        numList[i - 1] = i;
    }
}
like image 229
MartinMcfry Avatar asked Jan 21 '26 04:01

MartinMcfry


1 Answers

Your question has nothing to with sorting... but I think I understood what you are looking for, and the following code should provide it:

List<Int32> numbers = new List<Int32> { 1, 3, 3, 4 };
List<Int32> result = new List<Int32>(numbers.Count);

Int32 currentValue = 1;
Int32 lastNumber = numbers[0];

for (Int32 i = 0; i < numbers.Count; ++i)
{
    Int32 number = numbers[i];

    if (numbers[i] != lastNumber)
        ++currentValue;

    result.Add(currentValue);
    lastNumber = number;
}

foreach (Int32 number in result) 
    Console.WriteLine(number); // Output: 1, 2, 2, 3

Please, visit this link to try a working demo, which implements the following function:

private static List<Int32> IndexNumbers(List<Int32> input)
{
    List<Int32> numbers = input.OrderBy(x => x).ToList();
    List<Int32> result = new List<Int32>(input.Count);

    Int32 currentValue = 1;
    Int32 lastNumber = numbers[0];

    for (Int32 i = 0; i < numbers.Count; ++i)
    {
        Int32 number = numbers[i];

        if (numbers[i] != lastNumber)
            ++currentValue;

        result.Add(currentValue);
        lastNumber = number;
    }

    return result;
}
like image 139
Tommaso Belluzzo Avatar answered Jan 23 '26 19:01

Tommaso Belluzzo