How to use GroupBy () to group multiple columns using VB.NET?

I tried to do this, as in C #, with an anonymous type, but the result is simply incorrect.

Example VB.NET (incorrect 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 

Conclusion:

 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) 

Required Conclusion:

 Group [Age: 20, Sex: M] : 3 Item(s) Group [Age: 30, Sex: F] : 2 Item(s) 

C # example (correct conclusion):

 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 anyone see where my mistake is?

+6
source share
1 answer

When creating anonymous types in VB code, you need to use the Key modifier. By default, it creates read / write properties, while anonymous C # types are always read-only. Equals / GetHashCode uses only read-only properties.

 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 information .

+12
source

Source: https://habr.com/ru/post/918565/


All Articles