-2

I`ve got a struct that includes numeral variable

public struct A
{
    public int x;
    public string y;
}

Also i have a List of a struct type:List<A> l = new List<A>()

After adding noumerus elements into the list, a want to set a value to variable y but only for the element where x=1

I am able to find the element in the list that fullfill the condition

l.Find(item => item.x == 1) 

how i can to set the value of y for that specific element`? I tryed the elementary way (from my opinion) but it wrong

l.Find(item => item.x == 1).y="valueX"

Thank you in advance

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • 8
    Have you considered *not* using a struct, or making the struct immutable? (Yes there are ways of doing this, but I wouldn't recommend them.) – Jon Skeet May 15 '17 at 13:00
  • 5
    Don't try to change values of a a struct. That's a road to nowhere. You want a class. – Ralf May 15 '17 at 13:01
  • 3
    Since you have meaningless names anyway, maybe you are looking for a `Dictionary` instead. Then it's easy: `dict[1] = "valueX";` – Tim Schmelter May 15 '17 at 13:02

1 Answers1

4

This is a perfect example why using mutable strcuts is pure evil. Basically whenever your values might change you should consider to use a class instead of struct.

As of MSDN:

X DO NOT define mutable value types

The problem you got arises from the fact that structs are value-types which get copied whenever passed to or returned from a member - in your case List.Find. Thus any updates to the instance you recieved via Find won´t be reflected to the instance within the list. You could strangly bypass this by using an array instead of a list, but that´s also a bad idea as it hides the actual problem.

Community
  • 1
  • 1
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111