C# 多列实体框架 LINQ 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11836243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:26:19  来源:igfitidea点击:

Distinct on Multiple Columns Entity Framework LINQ

c#linqentity-frameworklinq-to-entities

提问by Nanu

What is the LINQ Equivalent of

什么是 LINQ 等价物

Select DISTINCT A, B, C from TESTDB WHERE ALPHA =1

I am trying something like this:

我正在尝试这样的事情:

var data = TESTDB.WHERE(i=>i.ALPHA==1).SELECT(A,B,C).DISTINCT();

采纳答案by Risky Martin

Using anonymous objects will do the trick:

使用匿名对象可以解决问题:

var data = TESTDB.Where(i => i.ALPHA == 1).Select(i => new {i.A, i.B, i.C}).Distinct();

回答by wlabaj

If you use it like that:

如果你这样使用它:

var list = new List<Pet>()
                       {
                           new Cat() {Name = "Kitty", Id = 1},
                           new Cat() {Name = "Kitty", Id = 1},
                           new Cat() {Name = "Kitty", Id = 1}
                       };

var distinctCount = list.Where(i => i.Id == 1).Distinct().Count();

it turns out that distinctCount equals 3. Why is that? Seems that by default Distinct distinguishes between instances (even though all properties have the same values they're three instances).

结果是distinctCount 等于3。这是为什么呢?似乎默认情况下 Distinct 区分实例(即使所有属性都具有相同的值,但它们是三个实例)。

You should implement custom comparer, here you'll find the code example: http://msdn.microsoft.com/en-us/library/bb338049.aspx.

您应该实现自定义比较器,在这里您可以找到代码示例:http: //msdn.microsoft.com/en-us/library/bb338049.aspx

Yet I'm not sure why do you want to select three properties (A,B,C). You can access single property in this way:

但是我不确定您为什么要选择三个属性(A、B、C)。您可以通过以下方式访问单个属性:

var data = list.Where(i => i.Id == 1).Distinct().SelectMany(i => i.Name);

However in order to select multiple properties you should cast the whole object to some class containing those properties:

但是,为了选择多个属性,您应该将整个对象强制转换为包含这些属性的某个类:

var data = list.Where(i => i.Id == 1).Cast<Pet>().Distinct().ToList();

回答by sherebry

You can also try

你也可以试试

db.Table
  .OrderBy(m=>m.Name)
  .DistinctBy(m=> new{m.SerialNumber, m.Manufacturer})
  .ToList();