发送一个序列LINQ项目返回void的方法 [英] Sending items in a LINQ sequence to a method that returns void
问题描述
通常情况下,而我处理LINQ序列,我想每一个项目发送到返回void的方法,避免foreach循环。但是,我还没有找到一个优雅的方式来做到这一点。今天,我写了下面的代码:
Often while I'm dealing with LINQ sequences, I want to send each item to a method returning void, avoiding a foreach loop. However, I haven't found an elegant way to do this. Today, I wrote the following code:
private StreamWriter _sw;
private void streamToFile(List<ErrorEntry> errors)
{
if (_sw == null)
{
_sw = new StreamWriter(Path.Combine
(Path.GetDirectoryName(_targetDatabasePath), "errors.txt"));
}
Func<ErrorEntry, bool> writeSelector =
(e) => { _sw.WriteLine(getTabDelimititedLine(e)); return true; };
errors.Select(writeSelector);
_sw.Flush();
}
正如你所看到的,我写的lambda函数,仅仅返回true,并我认识到,选择的方法会返回booleans-我就忽略该序列的序列。然而,这似乎有点noobish和JANK。是否有任何优雅的方式来做到这一点?还是我误用LINQ?
As you can see, I write a lambda function that just returns true, and I realize that the Select method will return a sequence of booleans- I'll just ignore that sequence. However, this seems a little bit noobish and jank. Is there any elegant way to do this? Or am I just misapplying LINQ?
感谢。
推荐答案
第一所有的,你当前的代码将无法正常工作。结果
选择
,和其他大多数LINQ的方法,使用延迟执行,这意味着它们实际上没有做任何事情,直到你列举的结果。
First of all, your current code will not work.
Select
, and most other LINQ methods, use deferred execution, meaning that they don't actually do anything until you enumerate the results.
在一般情况下,你不应该使用带有副作用LINQ查询的lambda。
In general, you should never use a lambda with side effects in a LINQ query.
要回答你的问题,你应该使用的foreach
循环。
To answer your question, you should use a foreach
loop.
您正在寻找一个的ForEach
扩展方法; 埃里克利珀解释了为什么微软没有写一个。
You're looking for a ForEach
extension method; Eric Lippert explains why Microsoft didn't write one.
如果你真的想,你可以写一个自己的:
If you really want to, you can write one yourself:
public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> action) {
if (sequence == null) throw new ArgumentNullException("sequence");
if (action == null) throw new ArgumentNullException("action");
foreach(T item in sequence)
action(item);
}
//Return false to stop the loop
public static void ForEach<T>(this IEnumerable<T> sequence, Func<T, bool> action) {
if (sequence == null) throw new ArgumentNullException("sequence");
if (action == null) throw new ArgumentNullException("action");
foreach(T item in sequence)
if (!action(item))
return;
}
这篇关于发送一个序列LINQ项目返回void的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!