0

How can i select distinct() based on one field?

I have the following LINQ expression, how can I select distinct by ID field. for some reason i used .Distinct() but keeps shown me a duplicate, I want to show just one record

 var customersbyName = await _context.vw_CustomerSearch.AsNoTracking()
                            .Where(c => c.Name.Contains(request.searchWord))   
                            .Distinct()
                            .ToListAsync();
kuka muk
  • 349
  • 2
  • 18
  • Does this answer your question? [LINQ's Distinct() on a particular property](https://stackoverflow.com/questions/489258/linqs-distinct-on-a-particular-property) – Shoejep Sep 23 '20 at 20:23

2 Answers2

1

try:

var customersbyName = await _context.vw_CustomerSearch.AsNoTracking()
                            .Where(c => c.Name.Contains(request.searchWord))
                            .Select(c => c.ID)
                            .Distinct()
                            .ToListAsync();
Joel Fleischman
  • 414
  • 2
  • 5
0

Distinct compare each column of the row, so if one column is different, the row is distinct for linq / sql.

You can try it with a GroupBy:

var customersbyName = await _context.vw_CustomerSearch.AsNoTracking()
  .Where(c => c.Name.Contains(request.searchWord))
  .GroupBy(i => i.ID)
  .Select(x => x.First())