我有一个LINQ to SQL查询,访问结果时遇到问题。如果没有"group"子句,它可以正常工作,但有了group子句,结果字段似乎就不见了。
var q = (from p1 in db.Personnel
join t2 in db.Table2 on p1.PKField equals t2.PKField
where p1.Active != true
group p1 by p1.PersonName into grouping
select grouping);
现在我尝试通过访问结果
foreach (var results in q)
{
string xx = results.EmailAddress //this line fails with the group by in the linq.
}
如果我从Linq语句中删除了group by,那么我就可以访问EmailAddress字段。
结果是IGrouping<out string, out Person>
而不是Person
。
如果你确定一个小组中的所有人都有相同的电子邮件地址,你可以使用:
foreach (var results in q)
{
string xx = results.First().EmailAddress;
}
如果您想访问群成员的所有电子邮件地址:
foreach (var results in q)
{
foreach (var item in results)
{
string xx = item.EmailAddress;
...
}
}
也许是这样的:
var q = (from p1 in db.Personnel
join t2 in db.Table2 on p1.PKField equals t2.PKField
where p1.Active != true
group p1 by p1.PersonName into grouping
select new
{
grouping.Key,
EmailAddress=grouping.Max (g =>g.EmailAddress)
}
);
foreach (var results in q)
{
string xx = results.EmailAddress;
}