你可以在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
@rsbarra:我们都写了几乎相同的示例代码,但您可以通过7秒打我: - ) – 2011-05-12 05:10:33
@elian:很有趣。 =]好的答案! – rsbarro 2011-05-12 05:12:13
非常感谢你们 – kakopappa 2011-05-12 05:25:37