//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;
}
}
}
我想减少上面两个foreach循环的执行时间。有没有比这更好的方法?
答案 0 :(得分:1)
我第一眼就看到了多个选项:
ToList()
,此处不需要,请参阅@ Shelby115的评论newClaimLink.Where(k=> k.ClaimLinkId == claim.Id)
可以替换为事先创建的字典newClaimLink.ToDictionary(k=> k.ClaimLinkId)
claims.Where(p => p.Id == claimLink.ClaimId)
答案 1 :(得分:1)
您可以删除 <select data-show-subtext="true" class=" selectpicker bs-select form-
control" data-live-search="true" data-size="8" name="drawing">
<option value=""></option>
<?php foreach($get_drawing as $row): ?>
<option data-subtext="" value="<?php echo $row->drawing_id; ?>" >
<?php echo $row->drawing_name;?>
<img width="22%" height="10%" class="" src="<?php
echo base_url('drawing/fabricator/admin_3/'.$row->image); ?>">
</img>
</option>
<?php endforeach; ?>
</select>
条件,因为以下if (claimRelationList.Any())
不会迭代空列表。
您已经知道foreach
在每个内容中都不为空,因为您已在上面初始化它。所以我会替换
claim.Children
使用
claim.Children = claim.Children != null && claim.Children.Any() ? newChildren.Concat(claim.Children) : newChildren;
。
答案 2 :(得分:0)
以上是我对上述问题的最佳答案。
//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
var newChildren = claims.Where(o => claimRelationList.Select(p => p.ClaimId).Contains(o.Id));
if (newChildren.Any())
{
claim.Children = claim.Children != null && claim.Children.Any() ? newChildren.Concat(claim.Children) : newChildren;
}
}
}
我用内部foreach循环的lambda表达式解决了我的问题,然后我必须将执行时间减少超过250ms。
感谢您的帮助