How do I remove duplicates from a C# array?

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

    If you needed to sort it, then you could implement a sort that also removes duplicates.

    Kills two birds with one stone, then.

    0 讨论(0)
  • 2020-11-22 08:52

    You could possibly use a LINQ query to do this:

    int[] s = { 1, 2, 3, 3, 4};
    int[] q = s.Distinct().ToArray();
    
    0 讨论(0)
  • 2020-11-22 08:52

    Generic Extension method :

    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;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题