简单的 C# foreach 到 LINQ 问题
目前有这个:
foreach (var series in Chart1.Series)
{
series.Enabled = false;
}
我想用一个简单的一行表达式来表达这一点。我认为这会起作用:
Chart1.Series.Select( series => series.Enabled = false);
然而,这没有任何效果。大概是因为我只是误解了 Select 的工作原理,这很好。
我的下一个想法是做类似 Chart1.Series.ForEach(series => series.Enabled = false) 的事情,但是 Chart1.Series 没有实现 IEnumberable (..或者至少 ForEach 不是一个可接受的调用方法)。
我不想做 Chart1.Series = Chart1.Series.ToList().ForEach( series => series.Enabled = false);
,但也许这是最简单的选择?
Currently have this:
foreach (var series in Chart1.Series)
{
series.Enabled = false;
}
I would like to express this in a simple, one line expression. I thought this would work:
Chart1.Series.Select( series => series.Enabled = false);
This doesn't have any effect, however. Presumably because I just misunderstood how Select was working, which is fine.
My next thought was to do something like Chart1.Series.ForEach( series => series.Enabled = false), but Chart1.Series does not implement IEnumberable (..or at least ForEach is not an acceptable method to call).
I'd rather not do Chart1.Series = Chart1.Series.ToList().ForEach( series => series.Enabled = false);
, but maybe that is the simplest option?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对于您想要执行的操作,
foreach
是首选。您正在迭代一系列元素并修改这些元素。这就是foreach
的用途。Linq 用于获取一个元素序列并根据某些标准/转换生成一个新序列。不是你所追求的。
The
foreach
is preferred for what you're trying to do. You're iterating over a sequence of elements and modifying the elements. That's whatforeach
is for.Linq is used to take one sequence of elements and generate a new sequence based on some criteria/transformation. Not what you're after.
简单,一行:)
Simple and one line :)
你的第一个 foreach 循环非常清晰并且有效,所以为什么需要用 LINQ 替换它,它不会更清晰或更快。
否则我想不会比你上面说的简单
your first foreach loop is pretty clear and it works, so why need to replace it with LINQ, it wont be more clear or faster.
Otherwise I dont think it will be simpler than what you say above
至于 Select 不起作用的具体原因,请记住 Select 返回一个
IEnumerable
,它是一个知道如何枚举的对象。换句话说,您引用了可以枚举的内容,但尚未被枚举。因此,如果您这样做:您将获得您想要的效果,因为现在您正在枚举 Series 并因此调用 Select 委托。当然,这是相当不直观的,这就是为什么 Select 通常不以这种方式使用的原因(否则每次枚举时,都会产生副作用,并且枚举多次会再次应用副作用。)
As to the specific reason your Select didn't work, bear in mind that Select returns an
IEnumerable<T>
, which is an object that knows how to enumerate. In other words, you have a reference to something that can enumerate, but that hasn't yet been enumerated. So if you take this:You'll get the effect you intended, because now you're enumerating the Series and therefore calling the Select delegate. This is rather non-intuitive, of course, which is why Select is typically not used in this way (otherwise every time you enumerate, you'll have side effects and enumerating more than once would apply the side effects again.)