Good afternoon, please tell me on this issue, there is a collection of values ​​of type Sensors

public class Sensor { public SensorType SensorType { get; set; } public int RegisterAddress { get; set; } public int BitNumber { get; set; } public int Position { get; set; } public int Value { get; set; } } 

How to change the Value for elements with a given SensorType?

    2 answers 2

     foreach (var sensor in sensors.Where(s => s.SensorType == selectedType)) sensor.Value = newValue; 

    If the collection is from structures (int for example), then it is better to do something like this:

      var list = new List<int>(); for (int i = 0; i < list.Count; i++) { if (someCondition) list[i] = newValue; } 
    • It works, but could not explain why in the same situation, if the sensors are List <int>, then when you try to assign a sensor value, the compiler gives a readonly local variable error? - Anton Popov
    • @AntonPopov supplemented the answer - Monk
    • Clear, thanks ... - Anton Popov
     sensors=sensors.Select(x=> { x.Value=x.SensorType==selectedType?newValue:x.value; return x; }); 
    • Wow, are you seriously writing code that there is only one space for this construction? - Monk
    • Space studio usually puts on closing curly braces :) - Zufir