Wednesday, March 9, 2016

Inject into LINQ expression for debugging

Console.WriteLine(info) is effective to see value as we loop through. But a LINQ expression or even its function lambda equivalent cannot use Console directly. So the following Injector extension is very useful.


Inject into LINQ
    public static class  Injector
    {
        public static  IEnumerable<T> Where<T>(this IEnumerable<T> source,Func<T,string> debug)
        {
            foreach (T t in source)
            {
                string info = debug(t);
                Console.WriteLine(info);
                yield return t;
            }
        }
    }
            var q = from i in new[]{ 1, 5, 7, 2, 9, 3 }
            where "where %2 "+i
                    where i % 2 == 0
                    where "select " + i
                    select i;
            q.ToList();

No comments:

Post a Comment