更改列表&LT内部一定价值; T> [英] Change some value inside the List<T>

查看:97
本文介绍了更改列表&LT内部一定价值; T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些列表(其中T是一个自定义类,类有一些属性)。
我想知道如何使用Lambda表达式来改变一个或多个值inide的,所以结果会是一样的foreach循环波纹管:

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:

注:列表中包含内部的多个项目(多行)

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

和这个LINQ查询(使用Lambda表达式),但它不是同为上foreach循环,它只返回从列表中1项(一行)!

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!

我要的是,它返回的所有项目(全部行)并且只有chnages一个合适的(在WHERE延伸方法(S)指定的项目。

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();

请注意:这两个例子是不一样的我重复一次,LINQ只返回1个项目(一列),这是我不想要,我需要的一切!从列表项目以及(像foreach循环,它仅做变化,但它不删除任何项)。

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> 列表< T> 第一。

You could use ForEach, but you have to convert the IEnumerable<T> to a List<T> first.

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

这篇关于更改列表&LT内部一定价值; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆