C# For循环未在整个循环持续时间内运行
我有一组循环,当数量被更新时,可以向集合列表添加或从集合列表中删除。 移除循环工作正常,但是添加循环只应用了较短的时间 这是循环C# For循环未在整个循环持续时间内运行,c#,loops,C#,Loops,我有一组循环,当数量被更新时,可以向集合列表添加或从集合列表中删除。 移除循环工作正常,但是添加循环只应用了较短的时间 这是循环 public async Task UpdateLineItemByOrderLineId(int orderLineId, int newQuantity) { var clientBasket = await GetBasketAsync(); var lineItem = clientBasket.OrderLines.F
public async Task UpdateLineItemByOrderLineId(int orderLineId, int newQuantity)
{
var clientBasket = await GetBasketAsync();
var lineItem = clientBasket.OrderLines.FirstOrDefault(x => x.OrderLineId == orderLineId);
if (newQuantity == 0)
{
foreach (var m in lineItem.DelegatesList.Where(f=>f.OrderLineId == orderLineId))
{
lineItem.DelegatesList.Remove(m);
}
_orderLinesRepository.Delete(lineItem);
_orderLinesRepository.Save();
}
else
{
lineItem.Quantity = newQuantity;
if (lineItem.DelegatesList.Count > newQuantity)
{
for (int i = lineItem.DelegatesList.Count - 1; i >= newQuantity; --i)
{
lineItem.DelegatesList.RemoveAt(i);
}
}
if (lineItem.DelegatesList.Count < newQuantity)
{
for (int z = 0; z <= newQuantity - lineItem.DelegatesList.Count; z++)
{
lineItem.DelegatesList.Add(new OrderDelegate());
}
}
await _basketRepository.SaveAsync();
}
}
public异步任务UpdateLineItemByOrderLineId(int-orderLineId,int-newQuantity)
{
var clientBasket=wait GetBasketAsync();
var lineItem=clientBasket.OrderLines.FirstOrDefault(x=>x.OrderLineId==OrderLineId);
如果(newQuantity==0)
{
foreach(lineItem.DelegatesList.Where中的var m(f=>f.OrderLineId==OrderLineId))
{
lineItem.DelegatesList.Remove(m);
}
_orderLinesRepository.Delete(行项目);
_orderLinesRepository.Save();
}
其他的
{
lineItem.Quantity=新建数量;
如果(lineItem.DelegatesList.Count>newQuantity)
{
对于(int i=lineItem.DelegatesList.Count-1;i>=newQuantity;--i)
{
行项目.DelegatesList.RemoveAt(i);
}
}
if(lineItem.DelegatesList.Count 对于(int z=0;z当您添加到lineItem.DelegatesList
时,您将增加lineItems.DelegatesList.Count
。这意味着它将只运行大约一半的次数
在开始循环之前,将计数存储在临时变量中,或者将项目添加到单独的列表中,然后将列表添加到行项目中。DelegatesList
for (int z = 0; z <= newQuantity - lineItem.DelegatesList.Count; z++)
{
lineItem.DelegatesList.Add(new OrderDelegate());
}
第五次运行时,4个新数量)
{
对于(int i=lineItem.DelegatesList.Count-1;i>=newQuantity;--i)
{
行项目.DelegatesList.RemoveAt(i);
}
}
if(lineItem.DelegatesList.Count 对于(int z=0;z从正在迭代的列表中删除或添加到列表中有时会导致问题。通常最好在迭代期间将要添加/删除的项目放入一个新列表,然后再执行删除/添加。我相信这是newQuantity-lineItem.DelegatesList.Count,更改为newQuantity您正在更改DelegateList、 通过向循环中的列表添加元素进行计数,这通常是问题的根源。
z <= newQuantity - lineItem.DelegatesList.Count;
else
{
lineItem.Quantity = newQuantity;
int initialCount = lineItem.DelegatesList.Count;
if (lineItem.DelegatesList.Count > newQuantity)
{
for (int i = lineItem.DelegatesList.Count - 1; i >= newQuantity; --i)
{
lineItem.DelegatesList.RemoveAt(i);
}
}
if (lineItem.DelegatesList.Count < newQuantity)
{
for (int z = 0; z <= newQuantity - initialCount; z++)
{
lineItem.DelegatesList.Add(new OrderDelegate());
}
}
await _basketRepository.SaveAsync();
}