Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I optimize the following code faster?

I have two list:

reports count 6000 and
invoices count 6000

I have loop like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

foreach (var item in reports) 
{
    item.SettlementProcessStatus =
        invoices.Any(t => t.InvoiceId == item.RelatedInvoiceId) 
           ? SettlementProcessStatus.Done 
           : SettlementProcessStatus.Error;
}

At first, this code has a good speed, but the higher the index, the slower it becomes.
what solutions are recommended to optimize it?

>Solution :

The performance problem is that your code has to iterate at least partially through invoices for each of your reports. To avoid this, first create a HashSet with all your invoice ID’s and then search in there instead of your list.

Assuming you have integer ID’s you could do:

var invoiceIds = new HasSet<int>(invoices.Select(x => x.InvoiceId));

foreach (var item in reports) 
    item.SettlementProcessStatus = invoiceIds.Contains(item.RelatedInvoiceId) ?
        SettlementProcessStatus.Done :
        SettlementProcessStatus.Error;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading