Linq debugging real-time output information expansion method (excerpt)

In this original

[Translation] how to debug a LINQ query in C #

Original linq statement:

var res = employees
.Where(e => e.Gender == "Male")
.Take(3)
.Where(e => e.Salary > avgSalary)
.OrderBy(e => e.Age);

 

Extension method:

        public static IEnumerable<T> LogLINQ<T>(this IEnumerable<T> enumerable, string logName, Func<T, string> printMethod)
        {
#if DEBUG
            int count = 0;
            foreach (var item in enumerable)
            {
                if (printMethod != null)
                {
                    Debug.WriteLine($"{logName}|item {count} = {printMethod(item)}");
                }
                count++;
                yield return item;
            }
            Debug.WriteLine($"{logName}|count = {count}");
#else    
             return enumerable;
#endif
        }

Instructions

var res = employees
    .LogLINQ("source", e => e.Name)
    .Where(e => e.Gender == "Male")
    .LogLINQ("logWhere", e => e.Name)
    .Take(3)
    .LogLINQ("logTake", e => e.Name)
    .Where(e => e.Salary > avgSalary)
    .LogLINQ("logWhere2", e => e.Name)
    .OrderBy(e => e.Age);

Description and explanation:

  • Each LINQ query operation after placement  LogLINQmethod. It can choose to print all of the items and totals by this operation.

  • logNamePrefix each output, you can easily see it written queries steps. I like to name it after the operation of the same name.

  • Fun<T,string>printMethodAllow to print the contents of any given project. In the example above, I chose to use  to print employee's name, when is  the time, in addition to the total, will not print anything.e=>e.Namenull

  • In order to optimize this method to make valid in debug mode (  #if DEBUG). In the release mode, it does nothing.

  • Each project in order to print, without waiting for the end, because of LINQ  lazy features. The following is a view of a single operating results Tip: Copy the entire output to  . Then use Ctrl + Shift + F (Find) and locate the log prefix (for example  ). In the Find dialog box, click the Find All Current in the Document . This will only display line and the log name prefix match.notepad++logWhere2

 

Guess you like

Origin www.cnblogs.com/missile/p/11095341.html
Recommended