1

I have a situation where i display a list of products for a customer. So, there are two kinds of products. So, if customer is registerd to two products, then both the products get displayed. So, I need to display distinct rows. I did this:

   var queryProducts = DbContext.CustomerProducts.Where(p => p.Customers_Id ==  
                                            customerID).ToList().Select(r => new
                           {
                               r.Id,
                               r.Products_Id,
                               ProductName = r.Product.Name,
                               ShortName = r.Product.ShortName,
                               Description = r.Product.Description,
                               IsActive = r.Product.IsActive

                           }).Distinct();

In this, customerID is the value that i get from dropdownlist. However, it still displays the same row twice. So, can you please let me know how i can display only distinct records.

Sayamima
  • 205
  • 1
  • 8
  • 24

3 Answers3

3

The most likely reasons could be that Distinct when called with no parameter by default compares all the public properties for equality. I suspect your Id is going to be unique. Hence the Distinct is not working for you.

You can try something like

myCustomerList.GroupBy(product => product.Products_Id).Select(grp => grp.First());

I found this as answers to

  1. How to get distinct instance from a list by Lambda or LINQ
  2. Distinct() with lambda?
Community
  • 1
  • 1
Ramesh
  • 13,043
  • 3
  • 52
  • 88
1

You can write an implementation of IEqualityComparer<CustomerProduct>. Once you've got that, then you can use this:

DbContext.CustomerProducts.Where(p => p.Customers_Id == customerId)
    .ToList()
    .Distinct(new MyComparer())
    .Select(r => new {
    // etc.

public class MyComparer : IEqualityComparer<CustomerProduct>
{
    // implement **Equals** and **GetHashCode** here
}

Note, using this anonymous comparer might work better for you, but it compares all properties in the anonymous type, not just the customer ID as specified in the question.

McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • Can that be done as an anonymous function without the separate method @dbaseman? – dumbledad Dec 10 '12 at 17:25
  • 1
    @dumbledad there isn't :(. I don't know of any way to do it inline using an anonymous function. http://stackoverflow.com/q/191013/1001985 – McGarnagle Dec 10 '12 at 17:30
1

Have a look at LINQ Select Distinct with Anonymous Types

I'm guessing r.ID is varying between the two products that are the same, but you have the same Products_Id?

Community
  • 1
  • 1
Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156