鲜明的LINQ与匿名类型(在VB.NET)鲜明、类型、NET、LINQ

2023-09-03 01:05:41 作者:国民男屌

假设被引用列表下面包含2个元素:

 暗淡国家=从C在列表_
                选择新用{.Country = c.Country,.CountryID = c.CountryID}
 

在code以上的回报。

  .Country =西班牙.CountryID = 1
.Country =西班牙.CountryID = 1
 

我怎样才能在不同的值?该国家查询应该只包含

  .Country =西班牙.CountryID = 1
 
关于vb net的界面刷新问题

解决方案

我只能假设你在使用匿名类型的死心塌地由亚历克斯·派克给出的答案是正确的。 (我已经upvoted它)。

不过,这归结为一个VB.NET VS C#编译器讨论。

在VB.NET,当一个匿名类型遇到只有那些声明为关键属性的属性可用于比较目的。因此,在VB.NET无按键,当你试图做一个鲜明的对比,将会发生什么。

阅读所有关于它在这里。

因此​​,首先,要回答你的问题,这个工程的与的匿名类型:

 暗淡国家=从C在列表中选择New随着{重点c.CountryId,c.Country} Distinct.ToList
 

这就是为什么freedompeace的回答完全不是那么回事。

C#但是编译器有一点不同。

当一个匿名类型遇到的一个比较操作是必要的C#编译器重写equals和GetHash code。它会遍历所有的匿名类型的公共属性的计算对象的哈希值code,以测试是否相等。

And你可以阅读更多有关在这里。

希望这回答了你的问题。

Supposing the referenced List below contains 2 elements:

Dim Countries = From c In List _
                Select New With { .Country = c.Country, .CountryID = c.CountryID }

the code above returns

.Country=Spain .CountryID = 1
.Country=Spain .CountryID = 1

How can i get the distinct values? The Countries query should contain only

.Country=Spain .CountryID = 1

解决方案

I can only assume you're dead set on the use of anonymous type as the answer given by Alex Peck is correct. (and I've upvoted it).

However, this boils down to a VB.NET vs C# compiler discussion.

In VB.NET, when an anonymous type is encountered only those properties declared as key properties can be used for comparison purposes. So in VB.NET without key, when you're attempting to do a distinct comparison, nothing will occur.

Read all about it here.

So first, to answer your question, this works with anonymous types:

Dim Countries = From c In List Select New With {Key c.CountryId, c.Country} Distinct.ToList

This is why freedompeace's answer doesn't quite work.

C# however the compiler is a little different.

When an anonymous type is encountered and a comparison operation is needed the c# compiler overrides Equals and GetHashCode. It will iterate over all of the public properties of the anonymous type to compute the object's hash code to test for equality.

And you can read more about that here.

Hope this answers your question.