Accepted answer

I think this should also work;

names.Distinct().ToList().ForEach( n => Console.WriteLine(n));


Here you go:

string[] names = {"hello", "hello", "stack", "stack", "overflow", "overflow"};  
var distinctNames = names.Distinct();

foreach(String distinctName in distinctNames) 


You can use Distinct.

Try this:

string[] names = {"hello", "hello", "stack", "stack", "overflow", "overflow"};
var uniqueNames = (from c in names select c).Distinct();
foreach(String s in uniqueNames) Console.WriteLine(uniqueNames);


Despite the fact that some answer was marked accepted i think i can add some important information about the unexpected problems that you can come across in situations there you have objects in array and you need distinction to be based on some property of that object.

LINQ's Distinct() function may fail to work properly in that situation, so you should use workaround like this(which give you the same result):

var elems = someArray.GroupBy(x => x.PropertyToCompare).Select(y => y.First());

You can read more here:


var duplicates = suppliers_arr
    .GroupBy(i => i)
    .Where(g => g.Count() > 1)
    .Select(g => g.Key); 
if(duplicates.Count() > 0){
    foreach (var d in duplicates)
        ModelState.AddFormError(string.Format("{0} is duplicated",d.ToString()));
     //no duplicates

Related Articles