How do I remove duplicates from a C# array?

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

    The following piece of code attempts to remove duplicates from an ArrayList though this is not an optimal solution. I was asked this question during an interview to remove duplicates through recursion, and without using a second/temp arraylist:

    private void RemoveDuplicate() 
    {
    
    ArrayList dataArray = new ArrayList(5);
    
                dataArray.Add("1");
                dataArray.Add("1");
                dataArray.Add("6");
                dataArray.Add("6");
                dataArray.Add("6");
                dataArray.Add("3");
                dataArray.Add("6");
                dataArray.Add("4");
                dataArray.Add("5");
                dataArray.Add("4");
                dataArray.Add("1");
    
                dataArray.Sort();
    
                GetDistinctArrayList(dataArray, 0);
    }
    
    private void GetDistinctArrayList(ArrayList arr, int idx)
    
    {
    
                int count = 0;
    
                if (idx >= arr.Count) return;
    
                string val = arr[idx].ToString();
                foreach (String s in arr)
                {
                    if (s.Equals(arr[idx]))
                    {
                        count++;
                    }
                }
    
                if (count > 1)
                {
                    arr.Remove(val);
                    GetDistinctArrayList(arr, idx);
                }
                else
                {
                    idx += 1;
                    GetDistinctArrayList(arr, idx);
                }
            }
    

提交回复
热议问题