我有一种情况,我要为客户显示产品列表。所以,有两种产品。因此,如果客户注册了两个产品,那么这两个产品都会显示。所以,我需要显示不同的行。我这样做了:
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 是我从下拉列表中获得的值。但是,它仍然两次显示同一行。那么,您能告诉我如何只显示不同的记录吗?
最佳答案
最可能的原因可能是 Distinct 在默认情况下不带参数调用时比较所有公共(public)属性是否相等。我怀疑您的 ID 将是独一无二的。因此,Distinct 不适合您。
你可以尝试类似的东西
myCustomerList.GroupBy(product => product.Products_Id).Select(grp => grp.First());
我发现这是对
的回答关于c# - LINQ 中的不同元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10476401/