如何使用LINQ鲜明的()与多个领域 [英] How to use LINQ Distinct() with multiple fields

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

问题描述

我有以下的 EF类从数据库导出(简体)

 类产品
{
     公共字符串产品编号;
     公共字符串产品名称;
     公共字符串categoryId;
     公共字符串类别名称;
}

产品编号是在主键的表

有关的数据库设计(我不能修改)做了一个糟糕的设计决定,我有的CategoryId 类别名称在此表中。

我需要一个的DropDownList 与(不同)的CategoryId 类别名称文字。因此,我采用以下code:

  product.Select(M = gt;新建{m.CategoryId,m.CategoryName})。鲜明的();

在逻辑上它应该创建的CategoryId 一个匿名对象和类别名称作为属性。在鲜明的()保证没有重复对(<​​code>的CategoryId ,类别名称)。

但实际上,这是行不通的。据我理解鲜明的()刚工作的时候,只有一个领域的集合中,否则它只是忽略它们...是正确的?有什么解决方法吗?谢谢!

更新

对不起产品是:

 列表&LT;产品与GT;产品=新的List&LT;产品及GT;();

我找到了一种替代的方式来获得相同的结果鲜明的()

  product.GroupBy(D =&gt;新建{d.CategoryId,d.CategoryName})
       。选择(M =&gt;新建{m.Key.CategoryId,m.Key.CategoryName})


解决方案

我假设你使用不同的像一个列表上的方法调用。您需要通过通过了ToList 物化它作为数据源使用结果查询您的DropDownList,例如。

  VAR distinctCategories =产品
                        。选择(M =&gt;新建{m.CategoryId,m.CategoryName})
                        。不同()
                        .ToList();
DropDownList1.DataSource = distinctCategories;
DropDownList1.DataTextField =类别名称;
DropDownList1.DataValueField =类别ID;

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 is the Primary Key of the table.

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

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

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).

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!

UPDATE

Sorry product is:

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

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})

解决方案

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";

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

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