我一直在使用从函数调用中返回的c#字符串[]数组。我可以强制转换为Generic集合,但我想知道是否有更好的方法,可能是使用临时数组。

从c#数组中删除重复项的最佳方法是什么?


当前回答

在下面找到答案。

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;
    }
}

这是基于我刚刚解决的一个测试的一点贡献,可能对这里其他顶级贡献者的改进有所帮助。 以下是我所做的事情:

I used OrderBy which allows me order or sort the items from smallest to the highest using LINQ I then convert it to back to an array and then re-assign it back to the primary datasource 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. 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. 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. 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.

其他回答

在下面找到答案。

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;
    }
}

这是基于我刚刚解决的一个测试的一点贡献,可能对这里其他顶级贡献者的改进有所帮助。 以下是我所做的事情:

I used OrderBy which allows me order or sort the items from smallest to the highest using LINQ I then convert it to back to an array and then re-assign it back to the primary datasource 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. 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. 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. 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.

public static int RemoveDuplicates(ref int[] array)
{
    int size = array.Length;

    // if 0 or 1, return 0 or 1:
    if (size  < 2) {
        return size;
    }

    int current = 0;
    for (int candidate = 1; candidate < size; ++candidate) {
        if (array[current] != array[candidate]) {
            array[++current] = array[candidate];
        }
    }

    // index to count conversion:
    return ++current;
}

测试了下面的&它工作。最酷的是,它还做了一个文化敏感搜索

class RemoveDuplicatesInString
{
    public static String RemoveDups(String origString)
    {
        String outString = null;
        int readIndex = 0;
        CompareInfo ci = CultureInfo.CurrentCulture.CompareInfo;


        if(String.IsNullOrEmpty(origString))
        {
            return outString;
        }

        foreach (var ch in origString)
        {
            if (readIndex == 0)
            {
                outString = String.Concat(ch);
                readIndex++;
                continue;
            }

            if (ci.IndexOf(origString, ch.ToString().ToLower(), 0, readIndex) == -1)
            {
                //Unique char as this char wasn't found earlier.
                outString = String.Concat(outString, ch);                   
            }

            readIndex++;

        }


        return outString;
    }


    static void Main(string[] args)
    {
        String inputString = "aAbcefc";
        String outputString;

        outputString = RemoveDups(inputString);

        Console.WriteLine(outputString);
    }

}

--AptSenSDET

下面这段代码试图从ArrayList中删除重复项,尽管这不是最佳解决方案。在一次面试中,我被问到通过递归删除重复项,而不使用第二个/temp数组列表:

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);
            }
        }

下面是HashSet<string>方法:

public static string[] RemoveDuplicates(string[] s)
{
    HashSet<string> set = new HashSet<string>(s);
    string[] result = new string[set.Count];
    set.CopyTo(result);
    return result;
}

不幸的是,这个解决方案也需要。net框架3.5或更高版本,因为HashSet直到该版本才被添加。你也可以使用array.Distinct(),这是LINQ的一个特性。