C# Foreach keep adding the same item to list

You are always accessing by index zero constantly. Options to correct:

  1. If you use foreach use:

    foreach (var material in materialUsed)
    {
        var deliveryModel = new DeliveredTaskModel();
        deliveryModel.Info = material.SubPartCode;
        deliveryModel.Description = material.Description;
        deliveryModel.Qty = material.Qty;
        deliveredTaskModel.Add(deliveryModel);
    }
    
  2. If you use by indexer change to for-loop:

    for(int i = 0; i < materialUsed.Count, i++)
    {
        var deliveryModel = new DeliveredTaskModel();
        deliveryModel.Info = materialUsed[i].SubPartCode;
        deliveryModel.Description = materialUsed[i].Description;
        deliveryModel.Qty = materialUsed[i].Qty;
        deliveredTaskModel.Add(deliveryModel);
    }
    
  3. Then it will be nicer to user property initializer:

    foreach (var material in materialUsed)
    {
        deliveredTaskModel.Add(new DeliveredTaskModel
        {
            Info = material.SubPartCode,
            Description = material.Description,
            Qty = material.Qty
        });
    }
    
  4. And then using linq you can achieve it with .Select

    var deliveredTaskModel = materialUsed.Select(material => new DeliveredTaskModel
        {
            Info = material.SubPartCode,
            Description = material.Description,
            Qty = material.Qty
        }).ToList();
    

I suggest you go with the last option :)

One last comment - your if statement (materialUsed.Count > 0) is redundant because if collection is empty it won't go into the loop


You are referencing the same fixed index in your loop:

deliveryModel.Info = materialUsed[0].SubPartCode;

You need to use the loop variable:

deliveryModel.Info = material.SubPartCode;

You should use the current item in each iteration of the foreach loop instead of referencing the list. Try this:

IList<DeliveredTaskModel> deliveredTaskModel = new List<DeliveredTaskModel>();

        if (materialUsed.Count > 0)
        {
            foreach (var material in materialUsed)
            {
                var deliveryModel = new DeliveredTaskModel();
                deliveryModel.Info = material .SubPartCode;
                deliveryModel.Description = material .Description;
                deliveryModel.Qty = material .Qty;
                deliveredTaskModel.Add(deliveryModel);
            }
        }

Tags:

C#

Foreach