LINQ中的不同元素

时间:2012-05-07 03:42:01

标签: c# 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是我从下拉列表中获得的值。但是,它仍然会显示相同的行两次。那么,请你告诉我如何只显示不同的记录。

3 个答案:

答案 0 :(得分:3)

最可能的原因可能是默认情况下,在没有参数的情况下调用Distinct会比较所有公共属性的相等性。我怀疑你的身份证会是独一无二的。因此,Distinct不适合你。

您可以尝试类似

的内容

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

我发现这是

的答案
  1. How to get distinct instance from a list by Lambda or LINQ
  2. Distinct() with lambda?

答案 1 :(得分: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。

答案 2 :(得分:1)

查看LINQ Select Distinct with Anonymous Types

我猜r.ID在两个相同的产品之间有所不同,但你有相同的Products_Id?