C
C#3y ago
Bujju

Modify property of object in List [Answered]

I have a struct like this:
public struct MyStruct
{
public ulong Id { get; set; }

public string MyProperty { get; set; }
}
public struct MyStruct
{
public ulong Id { get; set; }

public string MyProperty { get; set; }
}
And I have a List<MyStruct>. I want to modify MyProperty for a certain MyStruct in the list, using the Id property. I tried this:
MyList.Where(x => x.Id == id).ToList().ForEach(x => x.MyProperty = myVariable);
MyList.Where(x => x.Id == id).ToList().ForEach(x => x.MyProperty = myVariable);
But it didn't work.
5 Replies
TheBoxyBear
TheBoxyBear3y ago
MyStruct is a struct so you can't change the value of properties Loop or not Ir you need to edit the properties, make it a class to make it a reference type $ref
mtreit
mtreit3y ago
Yes, use a class if you want mutable properties. In general structs should be immutable. Now, knowing that a struct is passed by value (meaning a copy is made when you access it), you COULD achieve what you want even using structs - by mutating the copy and then putting that copy back into the list.
List<MyStruct> data = new();

for (int i = 0; i < 10; i++)
{
data.Add(new MyStruct { Id = (ulong)i, MyProperty = i.ToString() });
}

for (int i = 0; i < data.Count; i++)
{
var item = data[i];
item.MyProperty = item.MyProperty + " MODIFIED!";
data[i] = item;
}

foreach (var item in data)
{
Console.WriteLine(item.MyProperty);
}
List<MyStruct> data = new();

for (int i = 0; i < 10; i++)
{
data.Add(new MyStruct { Id = (ulong)i, MyProperty = i.ToString() });
}

for (int i = 0; i < data.Count; i++)
{
var item = data[i];
item.MyProperty = item.MyProperty + " MODIFIED!";
data[i] = item;
}

foreach (var item in data)
{
Console.WriteLine(item.MyProperty);
}
However, this is doing a bunch of extra work for no good reason - just use a class instead. You could also achieve this with ref locals if the data was an array instead of a list. Again though, I would just use a class or a record.
Bujju
BujjuOP3y ago
Thanks
Accord
Accord3y ago
✅ This post has been marked as answered!
Want results from more Discord servers?
Add your server