Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare in Linq

Tags:

c#

linq

I have a bunch of data in a database that i want to write a search function for. The problem is that i'm getting many duplicates. The data is structured in Names and Surnames and i want to only send one unique of both so if i have two people with the first name Foo, and surname Bar only one will show.

No matter how I think of it I always come back to that I need to compare them.

var names = db.People
      .Where(r => r.Name.Contains(q))
      .OrderBy(r=> r.Name)
       *Psuedo-Code*
       if((this.Name==next.Name)&&(this.surSame==next.Surname)
           toss next data and loop to next
       *Psuedo-Code*
      .Take(5);

Maybe a bit messy, but you get the idea what I want to achieve. Can I do this in some way or is there any better way to go about it?

like image 795
Tim Avatar asked Dec 05 '22 12:12

Tim


1 Answers

You could do this:

var names = db.People
    .Where(r => r.Name.Contains(q))
    .Select(r => new { Name = r.Name, Surname = r.Surname })
    .Distinct()
    .Take(5);

But if that won't work because you need the whole People record, you just want the first, I've done something like this with success:

var names = db.People
   .Where(r => r.Name.Contains(q))
   .GroupBy(r => new { Name = r.Name, Surname = r.Surname })
   .Select(g => g.First())
   .Take(5);
like image 161
Ann L. Avatar answered Dec 11 '22 23:12

Ann L.