views:

14

answers:

1

Let's say I have two entities:

Physician
Credentials

And a physician can have many credentials, such as Dr. Jones can have MD, DO, MPH as credentials. So I need to generate a report via Linq that concatenates the credentials into a single string. For example:

from p in Physicians
select
{
   p.Name
   p.Credentials (??? <- concatenated list of all credentials ?????)
}

I have played with "p.Credentials.Aggregate((a,b) => a.Abrev + ',' + b.Abrev)" to no avail, but I'm not sure I have the syntax correct.

A: 

Uhm.... I've not tested it, but you can try:

from p in Physicians
select
{
   p.Name,
   String.Join(",", p.Credentials.Select<Credentials, string>(c=>c.Abrev).ToArray())
}

Into the Select, I think x must be Credential, not Credentials...

EDIT

You need to move your objects into memory, try adding ToList() before make the Select

from p in Physicians.Include("Credentials").ToList()
select new
{
    p.Name,
    Credentials = String.Join(",", p.Credentials.Select<Credentials, string>(c=>c.Abrev).ToArray())
}
tanathos
The problem is Linq2Entities does not allow String.Join as this cannot be executed on SQL Server.
CodeGrue
You're right! I've updated my answer, try now!
tanathos
With Aggregate your synthax is similar to .Aggregate("", (a,b) => b.Abrev + ", " + a) but you also need to first apply ToList(), because LinqToEntities seems to not support Aggregate.
tanathos