Domanda

I have a LINQ to SQL query and I'm having trouble to access the results. Without the 'group' clause, it works fine, but with the group clause the resulting fields seems to be missing.

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);

Now I try to access the results via:

foreach (var results in q)
{
   string xx = results.EmailAddress //this line fails with the group by in the linq.
}

If I remove the group by from the Linq statement, then I can access the EmailAddress field.

È stato utile?

Soluzione

results is an IGrouping<out string, out Person> and not a Person.

If you are certain all the persons in a group have the same Email address, you can use:

foreach (var results in q)
{
   string xx = results.First().EmailAddress;
}

If you want to access all the email addresses for a group member:

foreach (var results in q)
{
   foreach (var item in results)
   {
     string xx = item.EmailAddress;
     ...
   }
}

Altri suggerimenti

Maybe something like this:

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;
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top