LINQ query2来自查询 [英] LINQ query2 from query
问题描述
我正在学习这本书:
使用C#4.0对对象进行LINQ
好,我的问题:
我有两堂课:联系人和 CallLog .看起来像这样:
I have two class: Contact and CallLog. It look like:
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().该方法返回一个带有联系人和CallLogs的简单List<>.
Two Class have method: SampleData(). This metod return a simple List<> with Contacts and CallLogs.
List<Contact> contacts = Contact.SampleData();
List<CallLog> callLogs = CallLog.SampleData();
我现在有一个查询,该查询返回的结果是按每个联系人(确切的联系人,呼叫次数大于0)的呼叫次数排序的.
I have now query, which return a result sort by numbers of calls foreach Contact (exactly contact, who calls more that 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");
}
}
它返回例如:
斯蒂芬打了5次电话
苏菲打了2次电话
汤姆打了5次电话
等...
现在我想按通话时间分组(5次,2次...),那么我在写下一个查询:
now I want to group by time of calls (5 times, 2 times ...), well i'm writin next query by query:
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
这篇关于LINQ query2来自查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!