[英]c# distinct doesn't work. what i'm doing wrong?
I'm developing an asp.net core application.我正在开发一个 asp.net 核心应用程序。
I have a code for getting property values.我有一个获取属性值的代码。
var properties = _context.Properties.Select(p => new {
p.Name,
Values = p.Values.Distinct()
}).Distinct();
But Distinct() doesn't work.但是 Distinct() 不起作用。 What I'm doing wrong?
我做错了什么?
The problem is that the second Distinct
does not know how to compare the items.问题是第二个
Distinct
不知道如何比较这些项目。 Probably you mean distinct by name, instead it does distinct by all the properties.可能您的意思是名称不同,而是所有属性都不同。
Instead of creating an anonymous type, create a named one (ie Property
).与其创建匿名类型,不如创建一个命名类型(即
Property
)。 Then declare a IEqualityComparer<T>
for this type:然后为此类型声明一个
IEqualityComparer<T>
:
class PropertyNameComparer : IEqualityComparer<Property>
{
public bool Equals(Property x, Property y) => x.Name.Equals(y.Name);
public int GetHashCode(Property p) => p.Name.GetHashCode();
}
(for sake of simplicity, I'm not handling nulls here.) (为简单起见,我不在这里处理空值。)
var properties = _context.Properties.Select(p => new Property {
Name = p.Name,
Values = p.Values.Distinct()
})
.AsEnumerable()
.Distinct(new PropertyNameComparer());
Note the .AsEnumerable()
to separate the query from the second Distinct
to make it LINQ-to-Objects, because EF cannot convert the IEqualityComparer<T>
to SQL.请注意
.AsEnumerable()
将查询与第二个Distinct
分开以使其成为 LINQ-to-Objects,因为 EF 无法将IEqualityComparer<T>
转换为 SQL。
But the real question is, why are you getting duplicate properties in the first place?但真正的问题是,为什么首先要获得重复的属性? And if you do, what do you want to happen to the values of the duplicates?
如果您这样做了,您希望重复项的值发生什么变化? Will they contain the same values or different values?
它们会包含相同的值还是不同的值? My implementation just takes the first property with its values and ignores the values of the duplicates.
我的实现只采用第一个属性及其值并忽略重复项的值。 Instead, you might want to group by name and to union the values.
相反,您可能希望按名称分组并合并值。 But that's not clear from your question.
但这从你的问题中并不清楚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.