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 does adding a new value to a linked list overwrite the existing content?
In all of your program, there is only a single student
object:
student st = {rand(), "test"};
(in main
).
The rest of your code creates a linked list containing a dozen pointers to this one object. When you inspect your list, you follow the pointers and print the same object 12 times.
(As an aside, it's not the act of adding to your linked list that overwrites content, it's these lines in main
:
st.num = rand();
st.name = "test";
Here you modify the contents of the lone student
in your program.)
In order to fix this, you need to create multiple student
objects, one per list element. The easiest way to do that is to make container
store a student
directly:
typedef struct container {
student data; // not a pointer
struct container *next;
} container;
And then adapt all your functions to work with this data structure.
C# List.Add overwrites previous objects
It happens because you are inserting the same reference of orderItemVM
to itemList
.
Also, you can set a default size for itemList
and boost performance.
var realData = await _context.OrderItem.ToListAsync();
var itemList = new List<OrderItemVM>(realData.Count);
And for this task, you can use LINQ:
public async Task<IActionResult> OrderOverview()
{
var realData = await _context.OrderItem.ToListAsync();
var itemList = realData.Select(item => new OrderItemVM
{
Id = item.Id,
OrderId = item.OrderId,
OrderName = _context.Order.Find(item.OrderId).OrderName,
ItemName = item.ItemNam,
}).ToList();
return View(itemList);
}
new item adding to List overriding the previous one
You're adding the same item over and over again, and because it's a reference type all entries in the list point to the same instance of EmailClass
.
Create a new instance in every loop iteration to fix that:
for (int j = 0; j < lst.Count; j++)
{
emailLst = new EmailClass();
emailLst.__EmailcstName = dtbl3.Rows[0]["cstm_name"].ToString();
emailLst.__EmailcstLName = dtbl3.Rows[0]["cstm_LName"].ToString();
emailLst.__EmailcstAddress = dtbl3.Rows[0]["cstm_Addr"].ToString();
emailLst.__EmailcstPhoneNo = dtbl3.Rows[0]["cstm_Phone"].ToString();
emailLst.__EmailcstCellNo = dtbl3.Rows[0]["cstm_CellNo"].ToString();
emailLst.__EmailcstskypId = dtbl3.Rows[0]["cstm_skypeId"].ToString();
emailLst.__EmailcstEmail = dtbl3.Rows[0]["cstm_email"].ToString();
emailLst.__EmailcstCountry = dtbl3.Rows[0]["cstm_country"].ToString();
emailLst.__EmailcstCity = dtbl3.Rows[0]["cstm_City"].ToString();
emailLst.__EmailcstZipcode =Convert.ToInt32( dtbl3.Rows[0]["cstm_ZipCode"].ToString());
emailLst.__EmailcstRemarks = dtbl3.Rows[0]["cstm_remarks"].ToString();
emailLst._EmailCartProdName = lst[j]._CartProdName;
emailLst._EmailCartProdPrice = lst[j]._CartProdPrice;
emailLst._EmailCartProdQnty = lst[j]._CartProdQnty;
emailLst._EmailCartProdCode = lst[j]._CartProdName;
emailLst._EmailTotalProdPrice = lst[j]._TotalProdPrice;
lstCstmer.Add(emailLst);
}
Why does adding a new value to dictionary overwrite previous values in it
You have only created one dictionary with
Dictionary<string, int> TMP = new Dictionary<string, int>();
when you add this dictionary to the Players
, you add a reference to the dictionary. This means that all entries refer to the same dictionary.
To fix the problem, you need to create a new dictionary on each iteration of the loop:
for (int i = 0; i < NumberOfPlayers; i++)
{
Console.WriteLine(i);
Dictionary<string, int> TMP = new Dictionary<string, int>();
TMP.Add("Player Target", 0 + (i * 3));
etc.
Adding object to a list causes overwriting of all previous values, despite new instantiation within loop
Try to replace
var PenIsland = new MessageVM(byte_mes, message_id);
with
var PenIsland = new MessageVM(new List<byte>(byte_mes), message_id);
This assigns each MessageVM
object its own List<byte>
instance.
List overwriting data on all positions
What does your code to add the two objects to the list look like? My guess is:
Gente professor = new Gente();
professor.Nome = "Fu";
Alunos.Add(professor);
professor.Nome = "Bar";
Alunos.Add(professor);
Which is incorrect. When you add reference types to a list, you're only adding a reference to the original object. In this case you're adding two references to the same object twice.
Therefore, when you modify the second object...you're also modifying the first.
A simple one-liner fix would be to re-initialize professor
before its second use:
Gente professor = new Gente();
professor.Nome = "Fu";
Alunos.Add(professor);
professor = new Gente();
professor.Nome = "Bar";
Alunos.Add(professor);
Adding to list overwrites previous object values in C#
Your name
backing field is static:
private static string name;
Don't do that. Just remove the static
modifier, it's not necessary.
Static members belong to the type, rather than the instance. This means all instances of Takeoff
share the same value of name
, whichever value was assigned last.
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);
}
Related Topics
How to Create and Connect Custom User Buttons/Controls With Lines Using Windows Forms
Detect If Deserialized Object Is Missing a Field With the Jsonconvert Class in Json.Net
How to Update the Current Line in a C# Windows Console App
Do You Need to Dispose of Objects and Set Them to Null
Correct Way to Load Assembly, Find Class and Call Run() Method
Execute Powershell Script from C# With Commandline Arguments
How to String.Format a Timespan Object With a Custom Format in .Net
Why Is Access to the Path Denied
Most Efficient Way to Randomly "Sort" (Shuffle) a List of Integers in C#
String Output: Format or Concat in C#
How to Tell Whether a Point Is to the Right or Left Side of a Line
Generating Random, Unique Values C#
C# Code to Validate Email Address
Difference Between Shadowing and Overriding in C#
How to Specify a Custom Location to "Search For Views" in ASP.NET MVC
Httpclient.Getasync(...) Never Returns When Using Await/Async