'How can I optimize the following code faster?
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 1:[1]
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;
Solution 2:[2]
Instead of using a list for invoices, use a dictionary that have the RelatedInvoiceId as its Key Value.
That avoids iterating trough all list items each item.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bill Tür stands with Ukraine |
| Solution 2 | MaMe |
