我正在学习这本书:
使用C#4.0 LINQ到对象
好的,我的问题:
我有两个课程:联系和 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; }
}
关系: Contact.Phone等于CallLog.Number
两个类有方法:SampleData()。该metod返回一个简单的List<>与联系人和CallLogs。
List<Contact> contacts = Contact.SampleData();
List<CallLog> callLogs = CallLog.SampleData();
我现在有查询,它返回一个结果排序,按照联系人的电话号码排序(完全是联系人,谁调用的是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次
苏菲打电话2次
汤姆打电话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个查询进行此查询的任何方式(按组分组不在两个查询中)?
答案 0 :(得分:0)
这是另一种方法:
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
答案 1 :(得分:0)
解决:
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);
}
}
}