4

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.

0

5 Answers 5

11

Here you go:

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

foreach(String distinctName in distinctNames) 
    Console.WriteLine(distinctName);
Sign up to request clarification or add additional context in comments.

Comments

6

I think this should also work;

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

4 Comments

Don't think you need .ToList() there.
@FabianTamp: I tested without ToList() on linq pad. It says 'System.Collections.Generic.IEnumerable<string>' does not contain a definition for 'ForEach' and no extension method 'ForEach' accepting a first argument of type 'System.Collections.Generic.IEnumerable<string>' could be found
ForEach() is on List<T>, not on IEnumerable<T> so .ToList() is needed if you want to use the ForEach method. Alternatively you can just write a foreach(){} as normal.
Hi @Kaf could you please guide me after removing the duplicate value how can I sort the data here in the above piece of code which you have shared?
2

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

Comments

2

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

Comments

0
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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.