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.

0

4 Answers 4

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();
Sign up to request clarification or add additional context in comments.

Comments

7

you can do the below

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

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

4 Comments

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();
I have edited my answer even if it was just to give to the OP the right direction to go
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<T> over ArrayList, which is outdated).
in this case the order is not important as you can see by looking at the output {2000,2011,2012,2009}
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);
    }

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.