问题描述
我试图做到这一点像我将在C#中,有一个匿名的类型,但结果却并不正确。
i tried to do this like i would in C#, with an anonymous type but the result is just not correct.
VB.NET例子(错误输出):
VB.NET example (wrong output):
Module Module1
Sub Main()
Dim ls As List(Of Employee) = New List(Of Employee)
ls.Add(New Employee With {.Age = 20, .Sex = "M"})
ls.Add(New Employee With {.Age = 20, .Sex = "M"})
ls.Add(New Employee With {.Age = 20, .Sex = "M"})
ls.Add(New Employee With {.Age = 30, .Sex = "F"})
ls.Add(New Employee With {.Age = 30, .Sex = "F"})
For Each item In ls.GroupBy(Function(k) New With {.Age = k.Age, .Sex = k.Sex})
Console.WriteLine(String.Format("Group [Age: {0}, Sex: {1}] : {2} Item(s)", item.Key.Age, item.Key.Sex, item.Count()))
Next
Console.ReadLine()
End Sub
Class Employee
Private _Age As Integer
Public Property Age() As Integer
Get
Return _Age
End Get
Set(ByVal value As Integer)
_Age = value
End Set
End Property
Private _Sex As String
Public Property Sex() As String
Get
Return _Sex
End Get
Set(ByVal value As String)
_Sex = value
End Set
End Property
End Class
End Module
输出:
Group [Age: 20, Sex: M] : 1 Item(s)
Group [Age: 20, Sex: M] : 1 Item(s)
Group [Age: 20, Sex: M] : 1 Item(s)
Group [Age: 30, Sex: F] : 1 Item(s)
Group [Age: 30, Sex: F] : 1 Item(s)
所需的输出:
Desired output:
Group [Age: 20, Sex: M] : 3 Item(s)
Group [Age: 30, Sex: F] : 2 Item(s)
C#示例(正确的输出):
C# example (correct output):
class Program
{
static void Main(string[] args)
{
List<Employee> ls = new List<Employee>();
ls.Add(new Employee { Age = 20, Sex = "M" });
ls.Add(new Employee { Age = 20, Sex = "M" });
ls.Add(new Employee { Age = 20, Sex = "M" });
ls.Add(new Employee { Age = 30, Sex = "F" });
ls.Add(new Employee { Age = 30, Sex = "F" });
foreach (var item in ls.GroupBy(k => new { Age = k.Age, Sex = k.Sex }))
{
Console.WriteLine(String.Format("Group [Age: {0}, Sex: {1}] : {2} Item(s)", item.Key.Age, item.Key.Sex, item.Count()));
}
Console.ReadLine();
}
class Employee
{
public int Age { get; set; }
public string Sex { get; set; }
}
}
没有任何人看到我的错误是?
does anybody see where my error is?
推荐答案
您需要在VB code创建匿名类型时使用键
修改。默认情况下它会创建读/写性能,而C#匿名类型的总是的只读。只有只读属性在用等号
/ GetHash code
。
You need to use the Key
modifier when creating the anonymous types in the VB code. By default it creates read/write properties whereas C# anonymous types are always read-only. Only read-only properties are used in Equals
/ GetHashCode
.
For Each item In ls.GroupBy(Function(k) New With { Key .Age = k.Age, _
Key .Sex = k.Sex})
有关详细信息,请参阅在VB 的文档匿名类型。
See the documentation for anonymous types in VB for more details.
这篇关于如何使用GROUPBY()组在多个列用VB.NET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!