如何将 LINQ Distinct() 与多个字段一起使用

2024-04-17

我有以下内容EF class从数据库导出(简化)

class Product
{ 
     public string ProductId;
     public string ProductName;
     public string CategoryId;
     public string CategoryName;
}

ProductId is the 首要的关键表的。

对于数据库设计者做出的错误设计决策(我无法修改它),我有CategoryId and CategoryName在此表中。

我需要一个下拉列表与(不同)CategoryId as Value and CategoryName as Text。因此我应用了以下代码:

product.Select(m => new {m.CategoryId, m.CategoryName}).Distinct();

从逻辑上讲,它应该创建一个匿名对象CategoryId and CategoryName作为属性。这Distinct()保证没有重复对(CategoryId, CategoryName).

但实际上是行不通的。据我了解Distinct()仅当集合中只有一个字段时才起作用,否则它只会忽略它们......这是正确的吗?有什么解决方法吗?谢谢!

UPDATE

Sorry product is:

List<Product> product = new List<Product>();

我找到了另一种方法来获得相同的结果Distinct():

product.GroupBy(d => new {d.CategoryId, d.CategoryName}) 
       .Select(m => new {m.Key.CategoryId, m.Key.CategoryName})

我假设您使用 unique 就像列表上的方法调用一样。您需要使用查询结果作为 DropDownList 的数据源,例如通过以下方式实现它ToList.

var distinctCategories = product
                        .Select(m => new {m.CategoryId, m.CategoryName})
                        .Distinct()
                        .ToList();
DropDownList1.DataSource     = distinctCategories;
DropDownList1.DataTextField  = "CategoryName";
DropDownList1.DataValueField = "CategoryId";

如果您需要真实对象而不是只有很少属性的匿名类型,另一种方法是使用GroupBy使用匿名类型:

List<Product> distinctProductList = product
    .GroupBy(m => new {m.CategoryId, m.CategoryName})
    .Select(group => group.First())  // instead of First you can also apply your logic here what you want to take, for example an OrderBy
    .ToList();

第三种选择是使用更多Linq'sDistinctBy https://github.com/morelinq/MoreLINQ/blob/master/MoreLinq/DistinctBy.cs.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 LINQ Distinct() 与多个字段一起使用 的相关文章

随机推荐