-2

If I have one array for example [1 4 3 7 4 9 5 1 5 6 3].

How to delete repetitive numbers and give in the output array like this [1 4 3 7 9 5 6]?

3
  • you can you distinct on linq Commented Jan 12, 2014 at 14:09
  • So what have you tried. A loop, a lambda, a set, LinQ. On the face of it this should be trivial. Commented Jan 12, 2014 at 14:10
  • you can also simply copy the array into a hash, the key is same as the value. the resulting will be all unique Commented Jan 12, 2014 at 14:14

5 Answers 5

5

Distinct()

var distinctArray = myArray.Distinct().ToArray();
Sign up to request clarification or add additional context in comments.

Comments

3

You can call your array in a HashSet<int> constructor. HashSet is a kind of optimized collection. It's constructor eliminates the non-unique elements.

Here an example in LINQPad;

var array = new[]{1, 4, 3, 7, 4, 9, 5, 1, 5, 6, 3};
HashSet<int> h = new HashSet<int>(array);
h.ToArray().Dump();

Here a result;

enter image description here

3 Comments

@Baldrick Where did you find that in the documentation?
@Magnus I didn't, it was an error. Apologies, original comment deleted.
I want to download LINQPad now :)
2

What about this :

int[] arr = { 1, 4, 3, 7, 4, 9, 5, 1, 5, 6, 3 };
foreach (int item in arr.Distinct())
{
    Console.WriteLine(item);
}

and you can also assign in a array like this:

int[] unique = arr.Distinct().ToArray();

Comments

2

Couple of suggestions found searching:

1.)

int[] s = { 1, 2, 3, 3, 4};
int[] q = s.Distinct().ToArray();

2.) The easiest solution will be to simply sort the array (takes O(n log n) with standard implementation if you may use them. otherwise consider making an easy randomized quicksort (code is even on wikipedia)).

Afterwards scan it for one additional time. During that scan simple eliminate consecutive identical elements.

If you want to do it in O(n), you can also use a HashSet with elements you have already seen. Just iterate once over your array, for each element check if it is in your HashSet.

If it isn't in there, add it. If it is in there, remove it from the array.

Note, that this will take some additional memory and the hashing will have a constant factor that contributes to your runtime. Althought the time complexity is better, the practical runtime will only be onyl be faster once you exceed a certain array size

Comments

1

If you, for whatever reason, do not want to use Linq:

List<int> distinctList = new List<int>();
foreach (var num in numberList)
{
    if (!distinctList.Contains(num))
    {
        distinctList.Add(num);
    }
}

2 Comments

HashSet would be preferably here, with O(1) lookup.
Absolutly. But Soner beat me to it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.