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

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


当前回答

泛型扩展方法:

public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer)
{
    if (source == null)
        throw new ArgumentNullException(nameof(source));

    HashSet<TSource> set = new HashSet<TSource>(comparer);
    foreach (TSource item in source)
    {
        if (set.Add(item))
        {
            yield return item;
        }
    }
}

其他回答

下面经过测试和工作的代码将从数组中删除重复项。你必须包括系统。集合名称空间。

string[] sArray = {"a", "b", "b", "c", "c", "d", "e", "f", "f"};
var sList = new ArrayList();

for (int i = 0; i < sArray.Length; i++) {
    if (sList.Contains(sArray[i]) == false) {
        sList.Add(sArray[i]);
    }
}

var sNew = sList.ToArray();

for (int i = 0; i < sNew.Length; i++) {
    Console.Write(sNew[i]);
}

如果你愿意,你可以把它打包成一个函数。

using System;
using System.Collections.Generic;
using System.Linq;


namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
             List<int> listofint1 = new List<int> { 4, 8, 4, 1, 1, 4, 8 };
           List<int> updatedlist= removeduplicate(listofint1);
            foreach(int num in updatedlist)
               Console.WriteLine(num);
        }


        public static List<int> removeduplicate(List<int> listofint)
         {
             List<int> listofintwithoutduplicate= new List<int>();


              foreach(var num in listofint)
                 {
                  if(!listofintwithoutduplicate.Any(p=>p==num))
                        {
                          listofintwithoutduplicate.Add(num);
                        }
                  }
             return listofintwithoutduplicate;
         }
    }



}

在下面找到答案。

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.

List<String> myStringList = new List<String> (); foreach (myStringArray中的字符串) { 如果(! myStringList.Contains (s)) { myStringList.Add(年代); } }

这是O(n²),这对于一个短列表来说没有什么关系因为它将被塞进一个组合中,但对于一个大的集合来说可能很快就会成为一个问题。

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

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