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
  • 281
  • 1
  • 5
  • 11

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
  • 24,430
  • 5
  • 58
  • 85
0
list = list.Select(x =>
{
      if(x.id == id)
      {
           x.data = newdata;
           break;
      }
      return x;
}
Parth Savadiya
  • 1,203
  • 3
  • 18
  • 40