I have two list:
reports count 6000 and
invoices count 6000
I have loop like this:
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;