Change some value inside the List<T>

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 inide of it by using Lambda Expressions, so the result will be the same as the foreach loop bellow:

NOTE: list contains multiple items inside (multiple rows)

        foreach (MyClass mc in list)  
        {
            if (mc.Name == "height")
                mc.Value = 30;
        }

And this the the linq query (using Lambda expressions), but its not the same as the upper foreach loop, it only returns 1 item (one row) from the list!

What I want is, that it returns all the items (all rows) and ONLY chnages the appropriate one (the items specified in the WHERE extention method(s).

list = list.Where(w => w.Name == "height").Select(s => { s.Value = 30; return s; }).ToList();

NOTE: these 2 example are not the same! I repeat, the linq only returns 1 item (one row), and this is something I dont want, I need all items from the list as well (like foreach loop, it only do changes, but it does not remove any item).


您可以使用ForEach ,但必须先将IEnumerable<T>转换为List<T>

list.Where(w => w.Name == "height").ToList().ForEach(s => s.Value = 30);

我可能会用这个(我知道它不是纯粹的linq),如果你想保留所有的项目,请保留对原始列表的引用,并且你应该找到更新后的值:

 foreach (var mc in list.Where(x => x.Name == "height"))  
     mc.Value = 30;

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 void SetHeights(this IEnumerable<MyClass> source, int value)
{
    foreach (var item in source)
    {
       if (item.Name == "height")
       {
           item.Value = value;
       }

       yield return item;
    } 
}

var result = list.SetHeights(30).ToList();
链接地址: http://www.djcxy.com/p/52752.html

上一篇: 使用Concat组合列表

下一篇: 更改List <T>中的某个值