How to Order a List with Duplicates Without Repeats

Spideregg 140 Reputation points
2023-10-27T01:16:48.6+00:00

test

I want to know how to sort it like this. My code was working for the last value. If I change the index to another value, it won't work.

List<int> list = new List<int>(); 
            list.Add(1);
            list.Add(2);
            list.Add(3);
            list.Add(4);
            list.Add(5);
            list.Add(6);
            list.Add(7);
            var duplicates = list.GroupBy(x => x).Where(group => group.Count() > 1).Select(group => group.Key).ToList();
            int listcount = list.Count();
            if (duplicates.Count > 0)
            {
                int firstDuplicate = duplicates.First();
                int index = list.IndexOf(firstDuplicate);
                int lastDuplicate = duplicates[duplicates.Count - 1]; 
                int lastindex = list.LastIndexOf(lastDuplicate);

                int nextValue = lastDuplicate + 1;
                for (int i = index + 1; i <= listcount; i++)
                {
                    list.Insert(i, nextValue);
                    nextValue++;
                }
                if (list.Count > listcount)
                {
                    int count = list.Count() - listcount;
                    list.RemoveRange(listcount, count);
                }
            }
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.