Change some value inside the List

前端 未结 7 1358
甜味超标
甜味超标 2020-12-07 22:23

I have some list (where T is a custom class, and class has some properties). I would like to know how to change one or more values inside of it by using Lambda Expressions,

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-07 22:53

    You could use a projection with a statement lambda, but the original foreach loop is more readable and is editing the list in place rather than creating a new list.

    var result = list.Select(i => 
       { 
          if (i.Name == "height") i.Value = 30;
          return i; 
       }).ToList();
    

    Extension Method

    public static IEnumerable SetHeights(
        this IEnumerable source, int value)
    {
        foreach (var item in source)
        {
           if (item.Name == "height")
           {
               item.Value = value;
           }
    
           yield return item;
        } 
    }
    
    var result = list.SetHeights(30).ToList();
    

提交回复
热议问题