LINQ分组帮助

时间:2011-05-12 04:48:34

标签: c# .net linq

我有一个这样的清单,

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    

我想通过使用TYPE

来计算从被叫到多少时间
TYPE            FROM            TO  COUNT
voice           CALLER_A    CALLER_B    2
voicemail       CALLER_A    CALLER_B    1
text            CALLER_A    CALLER_C    2

如何做到这一点。请建议

2 个答案:

答案 0 :(得分: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; }
}

答案 1 :(得分:1)

您可以在C#中对匿名类进行分组。我写了以下示例来说明这一点:

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