如何在多个字段中使用 LINQ Distinct() [英] How to use LINQ Distinct() with multiple fields

查看:54
本文介绍了如何在多个字段中使用 LINQ Distinct()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 EF 类 派生自数据库(简化)

I have the following EF class derived from a database (simplified)

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

ProductId 是表的主键.

对于数据库设计者做出的错误设计决定(我无法修改它),我在此表中有 CategoryIdCategoryName.

For a bad design decision made by the DB designer (I cannot modify it), I have CategoryId and CategoryName in this table.

我需要一个 DropDownList,其中(不同的)CategoryId 作为 ValueCategoryName 作为 Text.因此我应用了以下代码:

I need a DropDownList with (distinct) CategoryId as Value and CategoryName as Text. Therefore I applied the following code:

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

逻辑上它应该创建一个匿名对象,其中 CategoryIdCategoryName 作为属性.Distinct() 保证没有重复对(CategoryId, CategoryName).

which logically it should create an anonymous object with CategoryId and CategoryName as properties. The Distinct() guarantees that there are no duplicates pair (CategoryId, CategoryName).

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

But actually it does not work. As far as I understood the Distinct() works just when there is just one field in the collection otherwise it just ignores them...is it correct? Is there any workaround? Thanks!

更新

抱歉 product 是:

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

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

I found an alternative way to get the same result as Distinct():

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

推荐答案

我假设您使用 distinct 就像对列表的方法调用一样.您需要将查询结果用作 DropDownList 的数据源,例如通过 ToList 将其具体化.

I assume that you use distinct like a method call on a list. You need to use the result of the query as datasource for your DropDownList, for example by materializing it via ToList.

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

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

Another way if you need the real objects instead of the anonymous type with only few properties is to use GroupBy with an anonymous type:

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

第三种选择是使用 MoreLinq 的 DistinctBy.

A third option is to use MoreLinq's DistinctBy.

这篇关于如何在多个字段中使用 LINQ Distinct()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆