Dot-Net

如何使用 GroupBy() 通過 VB.NET 對多個列進行分組?

  • June 20, 2012

我嘗試像在 C# 中那樣使用匿名類型執行此操作,但結果不正確。

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

輸出:

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)

期望的輸出:

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

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; }
   }
}

有人看到我的錯誤在哪裡嗎?

在 VB 程式碼中創建匿名類型時需要使用Key修飾符。預設情況下,它創建讀/寫屬性,而 C# 匿名類型始終是只讀的。Equals/中僅使用只讀屬性GetHashCode

For Each item In ls.GroupBy(Function(k) New With { Key .Age = k.Age, _
                                                  Key .Sex = k.Sex})

有關詳細資訊,請參閱VB 中匿名類型的文件。

引用自:https://stackoverflow.com/questions/11121303