Skip to content
Advertisement

Return IEnumerable rather IEnumerable

I need to join two tables and get the data from one of the table using linq.

The join works fine but it returns IEnumerable <$IEnumerable><$Ojbect> and I need IEnumerable<$Object>

Here is the code:

(
    from med in meds
    join pres in prescriptions
    on med.Code equals pres.Code into latstPrescrptions
    let allPrescriptions = latstPrescrptions.Where(
        pres => pres.PatientId == patientId 
            && (pres.PrescriptionEndDate > DateTime.Now)  
            || pres.PrescriptionEndDate == null
    )
    select allPrescriptions
);

Thanks

Advertisement

Answer

In general, when you want to “flatten” a collection, SelectMany is the construct you’re looking for.

In LINQ Query Syntax, that’s accomplished with multiple from clauses:

    from med in meds
    join pres in prescriptions
    on med.Code equals pres.Code into latstPrescrptions
    let allPrescriptions = latstPrescrptions.Where(
        pres => pres.PatientId == patientId 
            && (pres.PrescriptionEndDate > DateTime.Now)  
            || pres.PrescriptionEndDate == null
    )
    from prescription in allPrescriptions
    select prescription

Or, more simply:

    from med in meds
    join pres in prescriptions
    on med.Code equals pres.Code into latstPrescrptions
    from prescription in latstPrescrptions.Where(
        pres => pres.PatientId == patientId 
            && (pres.PrescriptionEndDate > DateTime.Now)  
            || pres.PrescriptionEndDate == null
    )

Looking at your query a little more closely, you could probably just avoid the into clause and rely on the join output to give you what you want, though.

    from med in meds
    join pres in prescriptions
    on med.Code equals pres.Code
    where pres.PatientId == patientId 
            && (pres.PrescriptionEndDate > DateTime.Now)  
            || pres.PrescriptionEndDate == null
    select pres
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement