17

Possible Duplicate:
Remove duplicates from array

How to get distinct values from an array in C#

Community
  • 1
  • 1
AK Jani
  • 183
  • 1
  • 1
  • 4

4 Answers4

33

You could use the .Distinct() extension method.

var collectionWithDistinctElements = oldArray.Distinct().ToArray();
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
9

Using Distinct() function:

var distinctArray = myArray.Distinct().ToArray();
coder3521
  • 2,608
  • 1
  • 28
  • 50
Samich
  • 29,157
  • 6
  • 68
  • 77
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
            */
agarcian
  • 3,909
  • 3
  • 33
  • 55
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.

Amar Palsapure
  • 9,590
  • 1
  • 27
  • 46