Home > database >  Return IEnumerable<Object> rather IEnumerable<IEnumerable><Object>
Return IEnumerable<Object> rather IEnumerable<IEnumerable><Object>

Time:03-24

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

CodePudding user response:

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
  • Related