2012-06-20 26 views
6

मैंने ऐसा करने की कोशिश की जैसे मैं एक अज्ञात प्रकार के साथ सी # में होगा, लेकिन परिणाम सिर्फ सही नहीं है।VB.NET के साथ एकाधिक कॉलम पर समूह करने के लिए GroupBy() का उपयोग कैसे करें?

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) 

सी # उदाहरण (सही उत्पादन):

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

कोई भी देखता है कि मेरी त्रुटि कहां है?

उत्तर

12

वीबी कोड में अनाम प्रकार बनाते समय आपको Key संशोधक का उपयोग करने की आवश्यकता है। डिफ़ॉल्ट रूप से यह पढ़ने/लिखने वाले गुण बनाता है जबकि सी # अज्ञात प्रकार हमेशा केवल पढ़ने के लिए होते हैं। केवल पढ़ने-योग्य गुणों का उपयोग 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 देखें।

संबंधित मुद्दे