简体   繁体   English

linq distinct并选择新查询

[英]linq distinct and select new query

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伊万诺夫伊万
  • 1 Ivanov Ivan 1伊万诺夫伊万
  • 2 Petrov Petr 2彼得罗夫彼得
  • 3 Sidorov Ivan 3西多罗夫伊万
  • 3 Sidorov Ivan 3西多罗夫伊万

and i need result: 我需要结果:

  • 1 Ivanov Ivan 1伊万诺夫伊万
  • 2 Petrov Petr 2彼得罗夫彼得
  • 3 Sidorov Ivan 3西多罗夫伊万

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

DistinctBy DistinctBy

Download 下载

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

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接口的引用类型。

You could implement an IEqualitycomparer that .Distinct use to determine if the item already exist in the list. 您可以实现一个IEqualitycomparer,.Distinct用于确定该项是否已存在于列表中。 It can compare on attributes instead on the reference to the same object. 它可以比较属性而不是对同一对象的引用。

But I don't know if it works on anonymous types. 但我不知道它是否适用于匿名类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM