C# LINQ分组帮助
我有一张这样的清单C# LINQ分组帮助,c#,.net,linq,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 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
我该怎么做。请告知如果我正确理解了这个问题,类似这样的方法应该有效:
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; }
}
void Main()
{
var list=新列表();
添加(新的通话记录{Type=“voice”,From=“CALLER\u A”,To=“CALLER\u B”});
添加(新的CallRecord{Type=“text”,From=“CALLER\u A”,To=“CALLER\u C”});
添加(新的通话记录{Type=“voicemail”,From=“CALLER\u A”,To=“CALLER\u B”});
添加(新的通话记录{Type=“voice”,From=“CALLER\u A”,To=“CALLER\u B”});
添加(新的CallRecord{Type=“text”,From=“CALLER\u A”,To=“CALLER\u C”});
变量组=(来自列表中的cr)
按新{cr.Type,cr.From,cr.To}对cr进行分组
进入g
选择g);
foreach(组中的var组)
WriteLine(“{0}-Count:{1}”,group.Key,group.Count());
}
公共类呼叫记录
{
公共字符串类型{get;set;}
来自{get;set;}的公共字符串
{get;set;}的公共字符串
}
您可以在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
}
@rsbarra:我们都写了几乎相同的示例代码,但你比我快了7秒:-)@elian:很有趣。=]回答得好!
Voice CALLER_A Caller_B 2
Text CALLER_A Caller_C 2
VoiceMail CALLER_A Caller_B 1