通常在我处理LINQ序列时,我想将每个项目发送到返回void的方法,避免使用foreach循环.但是,我还没有找到一种优雅的方法来做到这一点.今天,我写了以下代码:
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();
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我编写了一个只返回true的lambda函数,我意识到Select方法将返回一个布尔序列 - 我将忽略该序列.然而,这看起来有点讽刺和下沉.有没有优雅的方法来做到这一点?或者我只是误用了LINQ?
谢谢.