2

Possible Duplicate:
Remove duplicates from array

I have an int array which contains a defined number of elements, all positive. I want to get an array from this one where all the elements appear only once. e.g. If the first array was something like {2000,2011,2011,2012,2009,2009,2000}, I want to get this {2000,2011,2012,2009}. How can I do this? I tried lots of things with for loops but I can't manage to do something good.

Community
  • 1
  • 1
Cippo
  • 1,001
  • 4
  • 14
  • 26

4 Answers4

8

With LINQ it's easy:

var intArray = new[] { 2000, 2011, 2011, 2012, 2009, 2009, 2000 };
var uniqueArray = intArray.Distinct().ToArray();

http://msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx

Another way is using Enumerable.GroupBy:

uniqueArray = intArray.GroupBy(i => i).Select(grp => grp.Key).ToArray();
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
7

you can do the below

var yourArray = yourArray.Distinct().ToArray();

http://msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx

Massimiliano Peluso
  • 26,379
  • 6
  • 61
  • 70
  • That will only create an IEnumerable, not an array. To return a new array you need to call ToArray on the result. Something like: `yourArray = yourArray.Distinct().ToArray();` – Wormbo May 31 '12 at 15:52
  • I have edited my answer even if it was just to give to the OP the right direction to go – Massimiliano Peluso May 31 '12 at 15:53
  • Note that the value returned by `Distinct` is not guaranteed to be ordered. If you want it ordered by the values, use `yourArray.Distinct().OrderBy(x=>x).ToArray()`. If maintaining the original insertion order is important, (as your example might suggest) you might want to take a slower option like Efthimis's (but I'd recommend `List` over `ArrayList`, which is outdated). – Tim S. May 31 '12 at 16:10
  • in this case the order is not important as you can see by looking at the output {2000,2011,2012,2009} – Massimiliano Peluso May 31 '12 at 16:13
2

Alternative way:

    int[] _array = new int[] {1, 2, 1,2}
    var myArray = new System.Collections.ArrayList();

    foreach(var item in _array){
        if (!myArray.Contains(item))
            myArray.Add(item);
    }
0

In addition to the other answers, you may want to look at a HashSet, especially if you know ahead of time you will have duplicate values.

NominSim
  • 8,447
  • 3
  • 28
  • 38