Sending items in a LINQ sequence to a method that returns void

Posted by generalt on Stack Overflow See other posts from Stack Overflow or by generalt
Published on 2010-03-12T02:02:47Z Indexed on 2010/03/12 2:07 UTC
Read the original article Hit count: 310

Filed under:
|

Hello all. 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();
    }

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?

Thanks.

© Stack Overflow or respective owner

Related posts about LINQ

Related posts about void