Issue with List.Add() only saving the last added item
You need to instantiate the Orderables
within the for loop; otherwise, you keep reusing the same instance in all iterations (and overwriting its properties each time).
AssociatedComboItems ai = new AssociatedComboItems();
List<Orderables> tempList = new List<Orderables>();
foreach (var t in comboBox1.Items)
{
ai.ComboBoxItem = t.ToString();
for (int i = 0; i < fpSpread1.ActiveSheet.RowCount; i++)
{
Orderables orderables = new Orderables(); // ← Instantiate here
orderables.Display = fpSpread1.ActiveSheet.Cells[i, 1].Text;
orderables.ShowInDSR = (bool)fpSpread1.ActiveSheet.Cells[i, 0].Value;
orderables.DisplayOrder = i;
tempList.Add(orderables);
}
ai.AssociatedItems = tempList;
tempList.Clear();
if(AssociatedItems == null)
AssociatedItems = new List<AssociatedComboItems>();
AssociatedItems.Add(ai);
}
Unrelated to the question: You might find object initializer syntax to be cleaner:
Orderables orderables = new Orderables
{
Display = fpSpread1.ActiveSheet.Cells[i, 1].Text,
ShowInDSR = (bool)fpSpread1.ActiveSheet.Cells[i, 0].Value,
DisplayOrder = i,
};
Why does my ArrayList contain N copies of the last item added to the list?
This problem has two typical causes:
Static fields used by the objects you stored in the list
Accidentally adding the same object to the list
Static Fields
If the objects in your list store data in static fields, each object in your list will appear to be the same because they hold the same values. Consider the class below:
public class Foo {
private static int value;
// ^^^^^^------------ - Here's the problem!
public Foo(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
In that example, there is only one int value
which is shared between all instances of Foo
because it is declared static
. (See "Understanding Class Members" tutorial.)
If you add multiple Foo
objects to a list using the code below, each instance will return 3
from a call to getValue()
:
for (int i = 0; i < 4; i++) {
list.add(new Foo(i));
}
The solution is simple - don't use the static
keywords for fields in your class unless you actually want the values shared between every instance of that class.
Adding the Same Object
If you add a temporary variable to a list, you must create a new instance of the object you are adding, each time you loop. Consider the following erroneous code snippet:
List<Foo> list = new ArrayList<Foo>();
Foo tmp = new Foo();
for (int i = 0; i < 3; i++) {
tmp.setValue(i);
list.add(tmp);
}
Here, the tmp
object was constructed outside the loop. As a result, the same object instance is being added to the list three times. The instance will hold the value 2
, because that was the value passed during the last call to setValue()
.
To fix this, just move the object construction inside the loop:
List<Foo> list = new ArrayList<Foo>();
for (int i = 0; i < 3; i++) {
Foo tmp = new Foo(); // <-- fresh instance!
tmp.setValue(i);
list.add(tmp);
}
My List.Add in C# keeps adding and rewriting all previous items
You are modifying a tweet
object and then adding it to the list, but you never switch to a different tweet
instance before modifying it again in the next loop, so essentially you are adding the same instance to the list again and again (remember: you add object references, not copies!) and just modify that single instance every time.
Why does adding a new value to list overwrite previous values in the list
You're using the same instance of the Tag
object inside the loop, so each update to the TagName
is to the same reference. Move the declaration inside the loop to get a fresh object on each pass of the loop:
foreach (string t in tagList)
{
Tag _tag = new Tag(); // create new instance for every iteration
_tag.tagName = t;
tags.Add(_tag);
}
For bonus part - when you change Tag
from class
to struct
copy operation (that happens when you call tags.Add(_tag)
) copies whole instance (essentially creating new one) unlike in original class
case when only reference to the same single instance is copied into the parameter of the call and then to the list's element (see C# pass by value vs. pass by reference for explanation on how struct
passed to method calls).
Why is only the last element added to list stored/printed in the following program in Kotlin?
That's because you reuse Person
object within a loop and your result list consists of multiple references to the same object. To make it work you should move val obj = Person()
inside the loop:
for (loop in 0..2) {
val obj = Person()
obj.personName = namesList[loop%3]
obj.personHobby = hobbyList[loop%3]
obj.personAge = loop * 20
listofPeople.add(obj)
}
Why does my list.append not permanently add my item?
You need to initialise your list before you repeatedly add items. The natural way to achieve this is to wrap your logic in a while
loop and add an option to end the loop, e.g. keyword "end".
Otherwise, as in your code, food = []
will initialise a new empty list each time.
food = []
while True:
food_choice = str(input("Do you want to add, remove, search, or end? "))
if food_choice.lower() == 'end':
break
if food_choice.lower() == 'add':
food_to_add = str(input("Which item would you like to add? "))
food.append(food_to_add)
print(food_to_add, "has been addded to your fridge list.")
print(food)
Example usage:
Do you want to add, remove, search, or end? add
Which item would you like to add? banana
banana has been addded to your fridge list.
['banana']
Do you want to add, remove, search, or end? add
Which item would you like to add? orange
orange has been addded to your fridge list.
['banana', 'orange']
Do you want to add, remove, search, or end? end
Related Topics
How to Compile a C# File with Roslyn Programmatically
Xunit.Net: Global Setup + Teardown
How am I Misusing the Null-Coalescing Operator? Is This Evaluating "Null" Correctly
How to I Apply Filter While Paginating in ASP.NET MVC and Entity Framework
Mvvm: Binding to Model While Keeping Model in Sync with a Server Version
Can a Dbcontext Enforce a Filter Policy
Embedding a File Explorer Instance in a Windows Forms Application Form
How to Reduce Memory Consumption of PDFptable with Many Cells
ASP.NET MVC Razor Render Without Encoding
System.Net.Webexception: the Remote Name Could Not Be Resolved:
Accessing All the Nodes in Treeview Control
JSONconvert.Serializeobject Always Return {} in Xamarinforms
How to Extract Subscript/Superscript Properly from a PDF Using Itextsharp
What Is the Use of Static Constructors
How to Convert a Class into Dictionary<String,String>
How to Add an Ampersand for a Value in a ASP.NET/C# App Config File Value