0

Ex. I want to modify the element in list that "id" is matched. I do like this.

for(int i=0;i<list.Count;i++){
    if(list[i].id==id){
        list[i].data = newData;
        break;
    }
}

Is there any shorter way to do?

Chayanin
  • 167
  • 1
  • 3
  • 9

2 Answers2

0

Convert your list to dictionary and use id as a key:

var dictionary = list.ToDictionary(o => o.id);
//...
dictionary[id].data = newData;
Backs
  • 23,679
  • 4
  • 50
  • 77
0
list = list.Select(x =>
{
      if(x.id == id)
      {
           x.data = newdata;
           break;
      }
      return x;
}
Parth Savadiya
  • 1,191
  • 2
  • 17
  • 37