Remove the same element from an array in C #

How to remove the same element from an array in C #?

eg. array{0,2,2,8,4,6,1,0,4} and the output will bearray{0,2,8,4,6,1}

+3
source share
4 answers
using System.Linq;
...
var output = array.Distinct().ToArray();

Without LINQ:

int[] array = new[] { 0, 2, 2, 8, 4, 6, 1, 0, 4 };

List<int> result = new List<int>();
foreach (int element in array)
{
    if (!result.Contains(element))
        result.Add(element);
}
int[] resultArray = result.ToArray();
+3
source

You can use LINQ and do myArray.Distinct().ToArray().

+6
source

, .NET2 # 2.

( HashSet<T> .NET2, Dictionary<K,V> O (1), .)

int[] input = new int[] { 0, 2, 2, 8, 4, 6, 1, 0, 4 };

int[] output = DistinctItems(input);  // 0, 2, 8, 4, 6, 1

// ...

public static T[] DistinctItems<T>(T[] input)
{
    Dictionary<T, bool> dict = new Dictionary<T, bool>(input.Length);

    return Array.FindAll(input, delegate(T item)
                                    {
                                        if (dict.ContainsKey(item))
                                            return false;

                                        dict.Add(item, true);
                                        return true;
                                    });
}
+1

, HashSet<T>. , , , . ...

0

All Articles