Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Foreach keep adding the same item to list

Tags:

c#

foreach

I am having issues with my simple foreach. I am trying to get data from the database to my list.

IList<DeliveredTaskModel> deliveredTaskModel = new List<DeliveredTaskModel>();
// lines of code 

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

when I set a breakpoint on the foreach. I can see that it has 4 different items in materialUsed. however, when I do this foreach, it simply adds 4x the same item to the grid.

I assume it keeps adding the same item, but why? Could someone explain?

like image 378
Катерина Avatar asked Apr 24 '17 08:04

Катерина


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.


4 Answers

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

like image 190
Gilad Green Avatar answered Nov 11 '22 15:11

Gilad Green


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;
like image 37
Kempeth Avatar answered Nov 11 '22 16:11

Kempeth


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);
            }
        }
like image 33
Connell.O'Donnell Avatar answered Nov 11 '22 14:11

Connell.O'Donnell


IList<DeliveredTaskModel> deliveredTaskModel = new List<DeliveredTaskModel>();
// lines of code 

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);
    }
}

materialUsed[0] is the first item of your list, and whetever the number of items the list has you take always the first, you should take the current item "material"

like image 45
gandalf Avatar answered Nov 11 '22 14:11

gandalf