17

Possible Duplicate:
Remove duplicates from array

How to get distinct values from an array in C#

asked Jan 11, 2012 at 8:04
2
  • 7
    .Distinct()? Questions with nothing in it deserve nothing more as an answer... Commented Jan 11, 2012 at 8:06
  • 3
    int[] MyArray = { 0, 0, 1, 2, 3, 3, 4}; int[] MyDistinctArray = MyArray.Distinct().ToArray(); Will give you MyDistinctArray = { 0, 1, 2, 3, 4} Commented Jun 22, 2015 at 4:34

4 Answers 4

34

You could use the .Distinct() extension method.

var collectionWithDistinctElements = oldArray.Distinct().ToArray();
answered Jan 11, 2012 at 8:05
Sign up to request clarification or add additional context in comments.

Comments

10

Using Distinct() function:

var distinctArray = myArray.Distinct().ToArray();
coder3521
2,6461 gold badge30 silver badges51 bronze badges
answered Jan 11, 2012 at 8:05

1 Comment

Your dinstincts are correct :)
6

Use the Distinct method in LINQ.

See http://msdn.microsoft.com/en-us/library/bb348436.aspx

 List<int> ages = new List<int> { 21, 46, 46, 55, 17, 21, 55, 55 };
 IEnumerable<int> distinctAges = ages.Distinct();
 Console.WriteLine("Distinct ages:");
 foreach (int age in distinctAges)
 {
 Console.WriteLine(age);
 }
 /*
 This code produces the following output:
 Distinct ages:
 21
 46
 55
 17
 */
answered Jan 11, 2012 at 8:09

Comments

2

Distinct should suffice your problem, but if you are doing this on custom object you will need to implement IEquatable<T> and will need to override GetHashCode() method to make it work.

answered Jan 11, 2012 at 8:18

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.