A simple C# / LINQ trick shown with Console.ReadLine()

I haven’t been working on Paint.NET v4.0 at all lately, but I have been reading, learning, and prototyping about a whole sleuth of things related to functional and asynchronous programming. One such topic is that of monads, which I have a blog entry almost completed on. However, I wanted to get a quick blog post to show something simple yet powerful. LINQ brings a lot of power to IEnumerable<T>, and in this case we’re going to map the console input into an IEnumerable<T>. Then we’ll use standard LINQ methods to only display those lines of text that have ".dll" in them. It’s a contrived example, but it’s easy enough to find more useful applications of this. I have to go in a minute, so I’ll throw this code up on the blog and let the conversation be driven from the comments.

public static class Extensions
{
    public static IEnumerable<T> ToList<T>(this Func<T> sampleFn)
    {
        while (true)
        {
            T val = sampleFn();
            yield val;
        }
    }

    public static IEnumerable<T> While<T>(this IEnumerable<T> list, Func<T, bool> whileFn)
    {
        foreach (T item in list)
        {
            if (whileFn(item))
                yield return item;
            else
                yield break;
        }
    }

    public static void Execute<T>(this IEnumerable<T> list)
    {
        foreach (T item in list) { }
    }

    public static IEnumerable<T> Do<T>(this IEnumerable<T> list, Action<T> action)
    {
        foreach (T item in list)
        {
            action(item);
            yield item;
        }
    }
}

class Program
{
    public static void Main()
    {
        Func<string> inputSampleFn = Console.ReadLine;

        var input = inputSampleFn.ToList()
                                 .While(s => s != null);

        var query = input.Select(s => s.ToLower())
                         .Where(s => s.Contains(".dll"));

        query.Do(s => Console.WriteLine(s))
             .Execute();
    }
}

Now, compile this to something like "dllFilter.exe". Then run, at the command line, "dir c:\windows | filter.exe". Neat 🙂

Advertisement