2011-05-12 6 views
1

나는 내가이 작업을 수행하는 방법에 LINQ 그룹화 도움

TYPE   FROM   TO COUNT 
voice   CALLER_A CALLER_B 2 
voicemail  CALLER_A CALLER_B 1 
text   CALLER_A CALLER_C 2 

TYPE

을 사용하기 위해 호출로부터 얼마나 많은 시간 수를 갖고 싶어이 같은 목록,

TYPE   FROM   TO 
voice   CALLER_A CALLER_B  
text   CALLER_A CALLER_C  
voicemail  CALLER_A CALLER_B  
voice   CALLER_A CALLER_B  
text   CALLER_A CALLER_C  

있습니다. 내가 제대로 질문을 이해한다면이 같은 일을해야,

답변

1

당신이 할 수있는 C#에서 annonymous 클래스의 그룹. 나는이 방법을 보여줍니다 다음 예제를 썼다 :

void Main() 
{ 
    // This is the list from your example. 
    var contactmoments = new List<ContactMoment> { 
     new ContactMoment { From = "CALLER_A", To = "Caller_B", Type = ContactType.Voice }, 
     new ContactMoment { From = "CALLER_A", To = "Caller_C", Type = ContactType.Text }, 
     new ContactMoment { From = "CALLER_A", To = "Caller_B", Type = ContactType.VoiceMail }, 
     new ContactMoment { From = "CALLER_A", To = "Caller_B", Type = ContactType.Voice }, 
     new ContactMoment { From = "CALLER_A", To = "Caller_C", Type = ContactType.Text } 
    }; 

    // Group by the properties 'From', 'To' and 'Type' 
    var groups = contactmoments.GroupBy(c => new { c.From, c.To, c.Type }); 

    // Write the properties of the key and the size of the group to the console. 
    foreach(var group in groups) 
    { 
     Console.WriteLine("{0,-15} {1,-15} {2,-15} {3}", group.Key.Type, group.Key.From, group.Key.To, group.Count()); 
    } 
} 

class ContactMoment 
{ 
    public string From { get; set; } 
    public string To { get; set; } 
    public ContactType Type { get; set; } 
} 

enum ContactType 
{ 
    Voice = 1, 
    Text = 2, 
    VoiceMail = 3 
} 

이 다음과 같은 출력 줄 것입니다 :

Voice   CALLER_A  Caller_B  2 
Text   CALLER_A  Caller_C  2 
VoiceMail  CALLER_A  Caller_B  1 
1

를 조언을 주시기 바랍니다 :

void Main() 
{ 
    var list = new List<CallRecord>(); 
    list.Add(new CallRecord { Type="voice", From="CALLER_A", To="CALLER_B" }); 
    list.Add(new CallRecord { Type="text", From="CALLER_A", To="CALLER_C" }); 
    list.Add(new CallRecord { Type="voicemail", From="CALLER_A", To="CALLER_B" }); 
    list.Add(new CallRecord { Type="voice", From="CALLER_A", To="CALLER_B" }); 
    list.Add(new CallRecord { Type="text", From="CALLER_A", To="CALLER_C" }); 

    var groups = (from cr in list 
        group cr by new {cr.Type, cr.From, cr.To} 
        into g 
        select g); 

    foreach(var group in groups) 
     Console.WriteLine("{0} - Count: {1}", group.Key, group.Count()); 
} 

public class CallRecord 
{ 
    public string Type { get; set; } 
    public string From { get; set; } 
    public string To { get; set; } 
} 
+0

@rsbarra : 우리는 모두 거의 같은 예제 코드를 작성을하지만 7 초 나를 이길 : -) –

+0

@elian : 꽤 재미. =] 좋은 대답입니다! – rsbarro

+0

고마워요. – kakopappa