How do I remove duplicates from a C# array?

后端 未结 27 2208
北海茫月
北海茫月 2020-11-22 07:53

I have been working with a string[] array in C# that gets returned from a function call. I could possibly cast to a Generic collection, but I was w

27条回答
  •  一向
    一向 (楼主)
    2020-11-22 08:25

    Find answer below.

    class Program
    {
        static void Main(string[] args)
        {
            var nums = new int[] { 1, 4, 3, 3, 3, 5, 5, 7, 7, 7, 7, 9, 9, 9 };
            var result = removeDuplicates(nums);
            foreach (var item in result)
            {
                Console.WriteLine(item);
            }
        }
        static int[] removeDuplicates(int[] nums)
        {
            nums = nums.ToList().OrderBy(c => c).ToArray();
            int j = 1;
            int i = 0;
            int stop = 0;
            while (j < nums.Length)
            {
                if (nums[i] != nums[j])
                {
                    nums[i + 1] = nums[j];
                    stop = i + 2;
                    i++;
                }
                j++;
            }
            nums = nums.Take(stop).ToArray();
            return nums;
        }
    }
    

    Just a bit of contribution based on a test i just solved, maybe helpful and open to improvement by other top contributors here. Here are the things i did:

    1. I used OrderBy which allows me order or sort the items from smallest to the highest using LINQ
    2. I then convert it to back to an array and then re-assign it back to the primary datasource
    3. So i then initialize j which is my right hand side of the array to be 1 and i which is my left hand side of the array to be 0, i also initialize where i would i to stop to be 0.
    4. I used a while loop to increment through the array by going from one position to the other left to right, for each increment the stop position is the current value of i + 2 which i will use later to truncate the duplicates from the array.
    5. I then increment by moving from left to right from the if statement and from right to right outside of the if statement until i iterate through the entire values of the array.
    6. I then pick from the first element to the stop position which becomes the last i index plus 2. that way i am able to remove all the duplicate items from the int array. which is then reassigned.

提交回复
热议问题