2012-05-07 41 views
0

我有一種情況,我顯示一個客戶的產品列表。所以,有兩種產品。所以,如果客戶註冊了兩種產品,那麼這兩種產品都會顯示出來。所以,我需要顯示不同的行。我這樣做:LINQ中不同的元素

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

在這,customerID是我從dropdownlist得到的值。但是,它仍然顯示相同的行兩次。所以,你能告訴我如何只顯示不同的記錄。

+0

你想要什麼屬性清晰到行動上? – Ramesh

回答

1

您可以編寫IEqualityComparer<CustomerProduct>的實現。一旦你得到了這一點,那麼你可以使用這個:

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 
} 

注意,使用這種匿名的比較器可能爲你工作好,但它的匿名類型中指定的所有屬性進行比較,不只是客戶ID這個問題。

+0

這可以作爲一個匿名函數來完成嗎?沒有單獨的方法@dbaseman? – dumbledad

+1

@dumbledad沒有:(。我不知道有任何方式使用匿名函數進行內聯操作。http://stackoverflow.com/q/191013/1001985 – McGarnagle