LINQ for beginners

101 LINQ Samples is certainly a good collection of examples. Also LINQPad might be a good way to play around with LINQ.


Well one thing that would make your sample more "LINQy" is an IEnumerable<string> for reading lines from a file. Here's a somewhat simplified version of my LineReader class from MiscUtil:

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public sealed class LineReader : IEnumerable<string>
{
    readonly Func<TextReader> dataSource;

    public LineReader(string filename)
        : this(() => File.OpenText(filename))
    {
    }

    public LineReader(Func<TextReader> dataSource)
    {
        this.dataSource = dataSource;
    }

    public IEnumerator<string> GetEnumerator()
    {
        using (TextReader reader = dataSource())
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                yield return line;
            }
        }
    }


    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

Now you can use that:

    var query = from line in new LineReader(filename)
                let items = line.Split('\t')
                let myInteger int.Parse(items[1]);
                where myInteger == 24809
                select line;

    using (TextWriter writer = File.CreateText(Application.StartupPath 
                                               + "\\temp\\test.txt"))
    {
        foreach (string line in query)
        {
            writer.WriteLine(line);
        }
    }

Note that it would probably be more efficient to not have the let clauses:

    var query = from line in new LineReader(filename)
                where int.Parse(line.Split('\t')[1]) == 24809
                select line;

at which point you could reasonably do it all in "dot notation":

    var query = new LineReader(filename)
                        .Where(line => int.Parse(line.Split('\t')[1]) == 24809);

However, I far prefer the readability of the original query :)

Tags:

C#

Linq