複数の値によるグループ化が VB.NET ではうまく機能しないことがわかりましたが、C# ではうまく機能します。これが私のコードです。私の VB.NET コードに何か問題がありますか?
ここに私のVB.NETコードがあります:
Sub Main
Dim empList As New List(Of Employee)()
empList.Add(New Employee() With _
{.ID = 1, .FName = "John", .Age = 23, .Sex = "M"c})
empList.Add(New Employee() With _
{.ID = 2, .FName = "Mary", .Age = 25, .Sex = "F"c})
empList.Add(New Employee() With _
{.ID = 3, .FName = "Amber", .Age = 23, .Sex = "M"c})
empList.Add(New Employee() With _
{.ID = 4, .FName = "Kathy", .Age = 25, .Sex = "F"c})
empList.Add(New Employee() With _
{.ID = 5, .FName = "Lena", .Age = 27, .Sex = "F"c})
empList.Add(New Employee() With _
{.ID = 6, .FName = "Bill", .Age = 28, .Sex = "M"c})
empList.Add(New Employee() With _
{.ID = 7, .FName = "Celina", .Age = 27, .Sex = "F"c})
empList.Add(New Employee() With _
{.ID = 8, .FName = "John", .Age = 28, .Sex = "M"c})
Dim query = empList.GroupBy(Function(x) New With { .Age=x.Age, .Sex= x.Sex}) _
.Select(Function(g) New With {g.Key, g.Count()})
For Each employee In query
Console.WriteLine(employee.Count)
Next employee
End Sub
Public Class Employee
Private privateID As Integer
Public Property ID() As Integer
Get
Return privateID
End Get
Set(ByVal value As Integer)
privateID = value
End Set
End Property
Private privateFName As String
Public Property FName() As String
Get
Return privateFName
End Get
Set(ByVal value As String)
privateFName = value
End Set
End Property
Private privateAge As Integer
Public Property Age() As Integer
Get
Return privateAge
End Get
Set(ByVal value As Integer)
privateAge = value
End Set
End Property
Private privateSex As Char
Public Property Sex() As Char
Get
Return privateSex
End Get
Set(ByVal value As Char)
privateSex = value
End Set
End Property
End Class
employee.Count の出力はすべて 1 です。これは間違っています。私はC#で試してみましたが、うまくいきました。結果は正しいです。
//Here are my C# code:
void Main()
{
var empList =new List<Employee>
{
new Employee {ID = 1, FName = "John", Age = 23, Sex = 'M'},
new Employee {ID = 2, FName = "Mary", Age = 25, Sex = 'F'},
new Employee {ID = 3, FName = "Amber", Age = 23, Sex = 'M'},
new Employee {ID = 4, FName = "Kathy", Age = 25, Sex = 'F'},
new Employee {ID = 5, FName = "Lena", Age = 27, Sex = 'F'},
new Employee {ID = 6, FName = "Bill", Age = 28, Sex = 'M'},
new Employee {ID = 7, FName = "Celina", Age = 27, Sex = 'F'},
new Employee {ID = 8, FName = "John", Age = 28, Sex = 'M'}
};
var query = empList.GroupBy(x => new { x.Age, x.Sex})
.Select(g=>new {g.Key, Count=g.Count()});
foreach (var employee in query )
Console.WriteLine(employee.Count);
}
public class Employee
{
public int ID {get;set;}
public string FName {get;set;}
public int Age {get;set;}
public char Sex {get;set;}
}