user2117650
user2117650

Reputation: 43

How to remove duplicates from an Array using LINQ

I'm a beginner in C# so I have a question, I have a lot of names in my database my question is how can I make script that shows the data of names with no doubles in LINQ? Here an example:

string[] names = {hello, hello, stack, stack, overflow, overflow};

I have no idea how to do this can someone create a simple script that shows it how to do. I can solve the rest myself.

Upvotes: 4

Views: 10174

Answers (5)

Georgii Gonchar
Georgii Gonchar

Reputation: 446

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: http://blog.jordanterrell.com/post/LINQ-Distinct()-does-not-work-as-expected.aspx

Upvotes: 2

Ifeanyi Chukwu
Ifeanyi Chukwu

Reputation: 3327

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()));
    }
}else{
     //no duplicates
}

Upvotes: 0

Kaf
Kaf

Reputation: 33809

I think this should also work;

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

Upvotes: 7

Colin Mackay
Colin Mackay

Reputation: 19175

Here you go:

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

foreach(String distinctName in distinctNames) 
    Console.WriteLine(distinctName);

Upvotes: 11

Iswanto San
Iswanto San

Reputation: 18569

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);

Upvotes: 2

Related Questions