【问题标题】:How to use GroupBy() to group over multiple columns with VB.NET?如何使用 GroupBy() 通过 VB.NET 对多个列进行分组?
【发布时间】:2012-06-20 22:08:35
【问题描述】:

我尝试像在 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; }
    }
}

有人知道我的错误在哪里吗?

【问题讨论】:

    标签: .net vb.net linq group-by


    【解决方案1】:

    在 VB 代码中创建匿名类型时需要使用Key 修饰符。默认情况下,它会创建读/写属性,而 C# 匿名类型始终是只读的。 Equals / GetHashCode 中只使用只读属性。

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

    有关详细信息,请参阅documentation for anonymous types in VB

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-04
      • 1970-01-01
      • 2022-01-11
      • 2021-11-22
      • 2016-12-27
      • 1970-01-01
      • 2016-04-30
      相关资源
      最近更新 更多