zoukankan      html  css  js  c++  java
  • 理解Linq查询

    using System;
    using System.Linq;
    static class Program
    {
        static double Square(double n)
        {
            Console.WriteLine("Computing Square(" + n + ")...");
            return Math.Pow(n, 2);
        }
    
        public static void Main()
        {
            int[] numbers = { 1, 2, 3 };
            var query =
              from n in numbers
              select Square(n); // query只是一个语句,下面的foreach才执行内容
            foreach (var n in query)
                Console.WriteLine(n); // 逐个执行Square(n);方法
    
            for (int i = 0; i < numbers.Length; i++)
                numbers[i] = numbers[i] + 10;
            Console.WriteLine("- Collection updated -");
            foreach (var n in query)
                Console.WriteLine(n);
    
            Console.ReadKey();
        }
    }
    

    执行结果

    Computing Square(1)...
    1
    Computing Square(2)...
    4
    Computing Square(3)...
    9
    - Collection updated -
    Computing Square(11)...
    121
    Computing Square(12)...
    144
    Computing Square(13)...
    169
    
    

    同样的query,下面的却变了。query只是一个静态的存储语句。
    当foreach的时候,才逐个执行查询结果。

    再看小例子

    using System;
    using System.Diagnostics;
    using System.Linq;
    static class Program
    {
        public static void Main()
        {
            var processes =
              Process.GetProcesses()
                .Where(process => process.WorkingSet64 > 20 * 1024 * 1024)
                .OrderByDescending(process => process.WorkingSet64)
                .Select(process => new {
                    process.Id,
                    Name = process.ProcessName
                });
    
            foreach (var item in processes)
                Console.WriteLine(item.Name);
    
            Console.ReadKey();
        }
    }
    

    通过图解,能够更加清晰它的流程。

  • 相关阅读:
    冲刺阶段 day1
    目标系统流程图 数据流图
    团队作业二
    校外实习报告(十二)
    校外实习报告(十一)
    第二周实习总结
    校外实习报告(十)
    校外实习报告(九)
    校外实习报告(八)
    校外实习报告(七)
  • 原文地址:https://www.cnblogs.com/jiqing9006/p/7019392.html
Copyright © 2011-2022 走看看