我有List对象填充了自定义结构的实例。
list.Add(new Mail("mail1", "test11", "path11"));
list.Add(new Mail("mail2", "test12", "path12"));
list.Add(new Mail("mail1", "test13", "path13"));
list.Add(new Mail("mail1", "test14", "path14"));
list.Add(new Mail("mail2", "test15", "path15"));
var q = from x in list
group x by x.Sender into g
let count = g.Count()
where count > 2
orderby count descending
select new { Sender = g.Key};
foreach (var x in q)
{
Console.WriteLine(x.Sender);
}
该代码的输出将是:
MAIL1
但是因为我需要处理每个基于某个属性(即Sender)的值可用两次以上(或者n次)的邮件项目,我需要一个查询来显示所有发生的项目通常比n(包括对相应邮件项目的引用。
在填写查询后,我很乐意做这样的事情:
foreach (var x in q)
{
Console.WriteLine(x.Sender + " - " + x.Path + " - " + x.Count);
}
我是LINQ的新手,但我确信这在某种程度上是可能的。
感谢您的帮助
此致 凯文
答案 0 :(得分:1)
包含要添加到匿名类型的属性。
var q = from x in list
group x by x.Sender into g
let count = g.Count()
where count > 2
orderby count descending
select new
{ // add your fields here
Sender = g.Key,
Path = ..., // not sure what you wanted here
Count = count,
Mails = g, // include the mails in the group
};
然后你可以用它做你想做的事。
foreach (var x in q)
{
// each x is a type with the fields
// Sender
// Path
// Count
// Mails
Console.WriteLine(x.Sender + " - " + x.Path + " - " + x.Count);
foreach (var mail in x.Mails)
{
// do something with each individual mail
}
}