C# linq distinct 并选择新查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9992117/
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
linq distinct and select new query
提问by alexandrovdi
I have a query
我有一个查询
var QP = (from a in QProductAllInfo select new { a.Id, a.Title, a.FullTitle}).Distinct();
Result is:
结果是:
- 1 Ivanov Ivan
- 1 Ivanov Ivan
- 2 Petrov Petr
- 3 Sidorov Ivan
- 3 Sidorov Ivan
- 1 伊万诺夫
- 1 伊万诺夫
- 2 彼得罗夫
- 3 西多罗夫·伊万
- 3 西多罗夫·伊万
and i need result:
我需要结果:
- 1 Ivanov Ivan
- 2 Petrov Petr
- 3 Sidorov Ivan
- 1 伊万诺夫
- 2 彼得罗夫
- 3 西多罗夫·伊万
采纳答案by Sandeep
Assuming that different Ids are always considered distinct you can try this.
假设不同的 ID 总是被认为是不同的,你可以试试这个。
I would probably write it in two querys. That way it is easy to debug and more readable. You can use MoreLinq.
我可能会写在两个查询中。这样就很容易调试并且更具可读性。您可以使用MoreLinq.
var temp = from a in QProductAllInfo select new { a.Id, a.Title, a.FullTitle}.ToList();
var result = temp.DistinctBy(i => i.Id);
You can also use
你也可以使用
Var result = temp.GroupBy(x => x.Id).Select(y => y.First());
回答by Andreas Lindgren
You could implement an IEqualitycomparer that .Distinct use to determine if the item already exist in the list. It can compare on attributes instead on the reference to the same object.
您可以实现一个 IEqualitycomparer, .Distinct 用于确定该项目是否已存在于列表中。它可以比较属性而不是对同一对象的引用。
But I don't know if it works on anonymous types.
但我不知道它是否适用于匿名类型。
回答by Mareek
If you have duplicates in QProductAllInfo, replacing your code by this should fix your problem.
如果您在 QProductAllInfo 中有重复项,用此替换您的代码应该可以解决您的问题。
var QP = from a in QProductAllInfo.Distinct()
select new { a.Id, a.Title, a.FullTitle };
if this doesn't work, you can use tuples instead of anonymous types like this:
如果这不起作用,您可以使用元组而不是像这样的匿名类型:
var QP = from a in QProductAllInfo
select Tuple.Create(a.Id, a.Title, a.FullTitle);
Applying the Distinct operator on anonymous types is useless because anonymous types are always reference types that donc implement the IEquatable interface.
对匿名类型应用 Distinct 运算符是没有用的,因为匿名类型始终是不实现 IEquatable 接口的引用类型。

