我有以下来自数据库的EF类(简化)
class Product
{
public string ProductId;
public string ProductName;
public string CategoryId;
public string CategoryName;
}
ProductId是表的主键。
对于数据库设计者做出的错误设计决定(我无法修改),我在表中有CategoryId和CategoryName。
我需要一个DropDownList的使用(不同)CategoryId的价值,并CategoryName为文本。因此,我应用了以下代码:
product.Select(m => new {m.CategoryId, m.CategoryName}).Distinct();
从逻辑上讲,它应该使用CategoryId和CategoryName作为属性创建一个匿名对象。在Distinct()保证有没有重复对(CategoryId,CategoryName)。
但实际上它不起作用。就我所理解的Distinct()作品而言,收藏中只有一个领域,否则就忽略了它们……对吗?有什么解决方法吗?谢谢!
更新
对不起,product是:
List<Product> product = new List<Product>();
我找到了一种获得与以下结果相同的替代方法Distinct():
product.GroupBy(d => new {d.CategoryId, d.CategoryName})
.Select(m => new {m.Key.CategoryId, m.Key.CategoryName})