我正在学习这本书:
LINQ to object Using c# 4.0
好的,我的问题是:
我有两个类:Contact和CallLog。它看起来像:
public class Contact
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public DateTime DateOfBirth { get; set; }
public string State { get; set; }
};
public class CallLog
{
public string Number { get; set; }
public int Duration { get; set; }
public bool Incoming { get; set; }
public DateTime When { get; set; }
}
关系:接触。Phone等于CallLog。
两个类有方法:SampleData()。这个方法返回一个简单的列表<>,其中包含Contacts和CallLogs。
List<Contact> contacts = Contact.SampleData();
List<CallLog> callLogs = CallLog.SampleData();
我现在有一个query,它返回一个结果,按每个Contact(确切地说是Contact,谁调用的次数大于0)的调用数排序。
var query = (from callLog in callLogs
group callLog by callLog.Number into g
select new
{
contact = contacts.Where(c=>c.Phone == g.Key),
how_much = g.Count(),
});
foreach(var q in query){
foreach(var qq in q.contact){
Console.WriteLine(qq.FirstName + " calls " + q.how_much + " times");
}
}
它返回例如:
Stephan呼叫5次
Sophie打了2次电话
Tom打了5次电话
等等……
现在我想按呼叫时间分组(5次,2次…),我正在编写下一个查询:
var query2 = from q in query
group q by q.how_much into g
select new
{
what_number = g.Key, // f.e 5 times
count_what_number = g.Count(), // 5 times have 2 person
who = g // collection for person
};
foreach (var q in query2)
{
Console.WriteLine(q.what_number + " calls have done: ( " + q.count_what_number + ") peoples"));
foreach (var qq in q.who)
{
foreach (var qqq in qq.contact)
{
Console.WriteLine(" " + qqq.FirstName);
}
}
}
结果:5 calls have done: (2 peoples):
Stephan
Tom
2 calls have done: (1 peoples):
Sophie
这是任何方式使这个查询1查询(组按组不是在两个查询)?
还有另一种方法:
List<Contact> contacts = Contact.SampleData();
List<CallLog> callLogs = CallLog.SampleData();
var q = from callLog in callLogs
group callLog by callLog.Number into g
join c in contacts on g.Key equals c.Phone
let row = new { g = g, c = c }
group row by row.g.Count() into g2
select new
{
People = g2.Select((x) => x.c.FirstName).ToArray(),
Count = g2.Key
};
foreach (var qq in q)
{
Console.WriteLine(qq.Count + ": " + string.Join(", ", qq.People));
}
打印如下内容:
4: Tom, John
2: Adam
已解决:
var query = (from callLog in callLogs
group callLog by callLog.Number into g
select new
{
who = contacts.Where(c => c.Phone == g.Key),
how_much = g.Count()
}).GroupBy(c=>c.how_much);
foreach (var q in query)
{
Console.WriteLine(q.Key + " " + q.Count());
foreach (var qq in q)
{
foreach (var qqq in qq.who)
{
Console.WriteLine(qqq.FirstName + " " + qqq.LastName);
}
}
}