[英]How to use GroupBy() to group over multiple columns with VB.NET?
i tried to do this like i would in C#, with an anonymous type but the result is just not correct. 我试图像在C#中那样使用匿名类型来执行此操作,但是结果只是不正确。
VB.NET example (wrong output): VB.NET示例(错误输出):
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
Output: 输出:
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# example (correct output): C#示例(正确的输出):
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? 有人看到我的错误在哪里吗?
You need to use the Key
modifier when creating the anonymous types in the VB code. 在VB代码中创建匿名类型时,需要使用
Key
修饰符。 By default it creates read/write properties whereas C# anonymous types are always read-only. 默认情况下,它创建读/写属性,而C#匿名类型始终是只读的。 Only read-only properties are used in
Equals
/ GetHashCode
. Equals
/ GetHashCode
仅使用只读属性。
For Each item In ls.GroupBy(Function(k) New With { Key .Age = k.Age, _
Key .Sex = k.Sex})
See the documentation for anonymous types in VB for more details. 有关更多详细信息,请参见VB中匿名类型的文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.