LINQ中的不同元素 [英] Distinct elements in LINQ
问题描述
我有我的地方展示的产品列表为客户的情况。这样,有两种产品。所以,如果客户是registerd两款产品,那么这两个产品得到展示。所以,我需要显示不同行。我这样做:
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();
在此,是的customerID我从DropDownList中获得的价值。然而,它仍显示两次相同的行。那么,能不能请你让我知道我可以只显示不同的记录。
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.
推荐答案
最有可能的原因可能是DISTINCT时调用默认无参数比较所有平等的公共属性。我怀疑你的ID将是唯一的。因此,分明是不为你工作。
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.
您可以尝试像
myCustomerList.GroupBy(产品= GT; product.Products_Id)。选择(GRP => grp.First());
我发现这是答案
- How to get distinct instance from a list by Lambda or LINQ
- Distinct() with lambda?
这篇关于LINQ中的不同元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!