C
Join ServerC#
help
Modify property of object in List [Answered]
BBujju10/14/2022
I have a struct like this:
And I have a
But it didn't work.
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);
But it didn't work.
TTheBoxyBear10/14/2022
MyStruct is a struct so you can't change the value of properties
TTheBoxyBear10/14/2022
Loop or not
TTheBoxyBear10/14/2022
Ir you need to edit the properties, make it a class to make it a reference type
TTheBoxyBear10/14/2022
$ref
Mmtreit10/14/2022
Yes, use a class if you want mutable properties. In general structs should be immutable.
Mmtreit10/14/2022
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.
Mmtreit10/14/2022
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);
}
Mmtreit10/14/2022
However, this is doing a bunch of extra work for no good reason - just use a class instead.
Mmtreit10/14/2022
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.
BBujju10/14/2022
Thanks
AAccord10/14/2022
✅ This post has been marked as answered!