Anne3 Anne3 - 3 years ago 95
C# Question

How can I update the value of a field in every row of a list?

I have this class:

public class Test
{
public string Id { get; set; }
public int Number { get; set; }
public int DoubleNumber { get; set; }
}


and a list

List<Test> myTestList;


How can I make the value of the field DoubleNumber in
myTestList
equal to twice the value of Number? Note that I am okay to create another list if that's needed.

Answer Source

If I understand your question correctly:

foreach(Test item in myList) {
  item.DoubleNumber = 2*item.Number;
}

Or, if it's ok, just remove the setter and modify the getter to return 2x Number:

public class Test
{
    public string Id { get; set; }
    public int Number { get; set; }
    public int DoubleNumber { get { return 2* this.Number; } } //completely remove setter
}

Or, if you still want to be able to modify DoubleNumber:

public class Test {
  private int m_num;
  private int m_doubleNum;

  public string Id {
    get;
    set;
  }
  public int Number {
    get {
      return this.m_num;
    }
    set {
      this.m_num = value;
      this.m_doubleNum = 2 * value; //when Number is set, update m_doubleNum too
    }
  }
  public int DoubleNumber {
    get {
      return this.m_doubleNum;
    }
    set {
      this.m_doubleNum = value; //allow manual setting of DoubleNumber
      //or maybe also modify Number here?
      //this.m_num = value / 2;
    }
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download