将条件lambda语句与列表上的foreach动作一起使用 [英] Using conditional lambda statements with a foreach Action on a list
问题描述
为什么我不能做这样的事情?
Why Cant I do something like this?
如果我有一个List<String> myList
项,我希望能够有条件地对每个成员执行以下操作:
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?
我正在尝试准备要转换为双精度的字符串列表,并且我希望空白项显示为"0.0",这样我就可以一次性转换整个列表.
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.
推荐答案
ForEach不可更改,它不会以任何方式更改数据结构.
ForEach is not mutable, it doesn't change the data structure in any way.
您可以:
- 使用索引自己处理循环
- 使用.Select和.ToList生成新列表(前提是您使用的是.NET 3.5)
第1个示例:
for (Int32 index = 0; index < myList.Count; index++)
if (myList[index].Trim().Length == 0)
myList[index] = "0.0";
使用.NET 3.5和Linq:
With .NET 3.5 and Linq:
myList = (from a in myList
select (a.Trim().Length == 0) ? "0.0" : a).ToList();
在.NET 3.5中,不使用Linq语法,而是使用Linq代码:
With .NET 3.5, not using the Linq-syntax, but using the Linq-code:
myList = myList.Select(a => (a.Trim().Length == 0) ? "0.0" : a).ToList();
编辑:如果要生成新的双打列表,也可以使用Linq一次性完成:
Edit: If you want to produce a new list of doubles, you can also do that in one go using Linq:
List<Double> myDoubleList =
(from a in myList
select (a.Trim().Length == 0 ? "0" : a) into d
select Double.Parse(d)).ToList();
请注意,使用"0.0"而不是仅使用"0"取决于小数点是句点字符.在我的系统上不是,所以我只用"0"代替,但是更合适的方法是将对Double.Parse的调用更改为采用显式的数字格式,例如:
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:
List<Double> myDoubleList =
(from a in myList
select (a.Trim().Length == 0 ? "0.0" : a) into d
select Double.Parse(d, CultureInfo.InvariantCulture)).ToList();
这篇关于将条件lambda语句与列表上的foreach动作一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!