How do I remove duplicates from a C# array?

后端 未结 27 2866
北海茫月
北海茫月 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:49

    -- This is Interview Question asked every time. Now i done its coding.

    static void Main(string[] args)
    {    
                int[] array = new int[] { 4, 8, 4, 1, 1, 4, 8 };            
                int numDups = 0, prevIndex = 0;
    
                for (int i = 0; i < array.Length; i++)
                {
                    bool foundDup = false;
                    for (int j = 0; j < i; j++)
                    {
                        if (array[i] == array[j])
                        {
                            foundDup = true;
                            numDups++; // Increment means Count for Duplicate found in array.
                            break;
                        }                    
                    }
    
                    if (foundDup == false)
                    {
                        array[prevIndex] = array[i];
                        prevIndex++;
                    }
                }
    
                // Just Duplicate records replce by zero.
                for (int k = 1; k <= numDups; k++)
                {               
                    array[array.Length - k] = '\0';             
                }
    
    
                Console.WriteLine("Console program for Remove duplicates from array.");
                Console.Read();
            }
    

提交回复
热议问题