在列表上使用条件 lambda 语句和 foreach 操作
为什么我不能做这样的事情?
如果我有一个 List
填充了项目,我希望能够以有条件的方式对每个成员进行操作,如下所示:
myList.ForEach(a => { if (a.Trim().Length == 0) a = "0.0"; })
但这不会编译。 我猜这与缺少返回值有关?
我正在尝试准备一个字符串列表以转换为双精度数,并且我希望空项目显示“0.0”,这样我就可以一次性转换整个列表。
Why Cant I do something like this?
If I have a List<String> myList
populated with items, I want to be able to act on each member in a conditional way like so:
myList.ForEach(a => { if (a.Trim().Length == 0) a = "0.0"; })
But this will not compile. Im guessing its something to do with missing a return value?
Im trying to prepare a list of strings for conversion to doubles, and I want the empty items to show '0.0' so I can just convert the whole list in one go.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
ForEach 是不可变的,它不会以任何方式改变数据结构。
您可以:
#1 示例:
使用 .NET 3.5 和 Linq:
使用 .NET 3.5,不使用 Linq 语法,而是使用 Linq 代码:
编辑:如果您想生成一个新的双精度列表,您也可以使用 Linq 一次性完成此操作:
请注意,使用“0.0” " 而不仅仅是“0” 依赖于小数点作为句号。 在我的系统上不是,所以我将其替换为“0”,但更合适的方法是更改对 Double.Parse 的调用以采用显式数字格式,如下所示:
ForEach is not mutable, it doesn't change the data structure in any way.
You can either:
Example of #1:
With .NET 3.5 and Linq:
With .NET 3.5, not using the Linq-syntax, but using the Linq-code:
Edit: If you want to produce a new list of doubles, you can also do that in one go using Linq:
Note that using "0.0" instead of just "0" relies on the decimal point being the full stop character. On my system it isn't, so I replaced it with just "0", but a more appropriate way would be to change the call to Double.Parse to take an explicit numeric formatting, like this:
您可能想要的是:
允许:
只需将
MutateEach
方法放入您自己的公共静态类中,并确保您有一个可以找到它的 using 指令。是否值得定义这样的东西取决于您使用它的频率。 请注意,它必须是
IList
的扩展,而不是IEnumerable
,这样我们才能执行更新,这使得它的应用范围不太广。What you possibly want is:
Which would allow:
Just put the
MutateEach
method in a public static class of your own and make sure you have a using directive that will find it.Whether it's worth defining something like this depends on how often you'd use it. Note that it has to be an extension on
IList
instead ofIEnumerable
, so we can perform the updates, which makes it less widely applicable.@daniel-earwicker 的
MutateEach
扩展解决方案是一个很好的解决方案。不过,要返回新的
List
,您可以选择使用List.ConvertAll(Converter(Func))
,自 .NET 2.0 以来一直存在。它不是 Linq 或 Lambda。
MSDN 参考 - List.ConvertAll
@daniel-earwicker's
MutateEach
Extension solution is a good solution.Though, for returning a new
List
, you have the option to useList.ConvertAll<TTo>(Converter<TFrom,TTo>(Func<TFrom, TTo>))
, which has been around since .NET 2.0.It is not Linq, or Lambda.
MSDN Reference - List.ConvertAll