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;
}
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With