Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce execution time in two foreach loop

//Get linked claim for children list from ClaimLink
foreach (var claim in processedClaims)
{
    if (claim.Children == null)
    {
        claim.Children = new List<Claim>();
    }
    var claimRelationList = newClaimLink.Where(k=> k.ClaimLinkId == claim.Id).ToList();
    if (claimRelationList.Any())
    {
        //Get the claim for all selected ClaimLink
        foreach (var claimLink in claimRelationList)
        {
            var newChildren = claims.Where(p => p.Id == claimLink.ClaimId).ToList();
            claim.Children = claim.Children != null && claim.Children.Any() ? newChildren.Concat(claim.Children) : newChildren;
        }
    }
}

I want to reduce the execution time in above two foreach loop. Is there have better way than this?

like image 992
Chamara Madhamperuma Avatar asked May 01 '26 12:05

Chamara Madhamperuma


2 Answers

You can remove the if (claimRelationList.Any()) condition as the following foreach will not iterate over an empty list. You already know that claim.Children is not null within that for each because you initialized it above. So I would replace

claim.Children = claim.Children != null && claim.Children.Any() ? newChildren.Concat(claim.Children) : newChildren;

With

claim.Children.AddRange (newChildren).

like image 151
Jason G. Avatar answered May 04 '26 01:05

Jason G.


Multiple options i see at first sight:

  1. don't call ToList(), not necessary here unless you have some sort of query executing in the background, see comment of @Shelby115
  2. newClaimLink.Where(k=> k.ClaimLinkId == claim.Id) could be replaced by a dictionary created beforehand like newClaimLink.ToDictionary(k=> k.ClaimLinkId)
  3. same goes for claims.Where(p => p.Id == claimLink.ClaimId)
like image 22
ViRuSTriNiTy Avatar answered May 04 '26 02:05

ViRuSTriNiTy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!