2

I have method as below:

public static IList<MedicalRecord> UpdateServicePrice(
                         IList<MedicalRecord> mListMedicalRecord, 
                         IList<ServicePrice> listAllServicePrice)
{
    foreach (MedicalRecord medical in mListMedicalRecord)
    {
        medical.mListServicePrice =
            (from p in listAllServicePrice
             where p.MedicalRecordID == medical.MedicalRecordID
            select p).ToList();
    }
    return mListMedicalRecord;
}

but it run very slow. Any one can help me for improve performance of above method? Thank a lot.

Jan
  • 15,802
  • 5
  • 35
  • 59

2 Answers2

3

Here's a Join-based method that should achieve the same thing, but faster:

public static IList<MedicalRecord> UpdateServicePrice(
    IList<MedicalRecord> mListMedicalRecord,
    IList<ServicePrice> listAllServicePrice)
{
    foreach (var j in mListMedicalRecord.GroupJoin(listAllServicePrice,
        mr => mr.MedicalRecordID,
        sp => sp.MedicalRecordID,
        (mr, sps) => new { Record = mr, Prices = sps }))
    {
        j.Record.mListServicePrice = j.Prices.ToList();
    }
    return mListMedicalRecord;
}

Your code loops through the ServicesPrices once for each MedicalRecord. Join goes through the prices once, grouping them by the record ID, and then joins them to the correct record.

Rawling
  • 49,248
  • 7
  • 89
  • 127
0

You might get significant improvement by replacing the 'where' with a 'join' clause.

JohnC
  • 844
  • 4
  • 10
  • 1
    @ssg, this: http://stackoverflow.com/questions/5551264/why-is-linq-join-so-much-faster-than-linking-with-where – tranceporter Nov 29 '12 at 14:19
  • @tranceporter: thanks I know about the behavior. I wasn't sure JohnC was referring to it. http://stackoverflow.com/questions/649444/testing-equality-of-arrays-in-c-sharp#comment3006817_649476 – Sedat Kapanoglu Nov 29 '12 at 18:39