zoukankan      html  css  js  c++  java
  • LINQ查询表达式(2)

    在 C# 中编写 LINQ 查询

      C# 中编写 LINQ 查询的三种方式:

    • 使用查询语法。
    • 使用方法语法。
    • 组合使用查询语法和方法语法。
            // 查询语法
                IEnumerable<int> filteringQuery =
                    from num in numbers
                    where num < 3 || num > 7
                    select num;
    
            // 方法语法.
                IEnumerable<int> largeNumbersQuery = numbers2.Where(c => c > 15); 
           //混合语法
                int numCount1 =
                    (from num in numbers1
                     where num < 3 || num > 7
                     select num).Count();
    
                // Better: Create a new variable to store
                // the method call result
                IEnumerable<int> numbersQuery =
                    from num in numbers1
                    where num < 3 || num > 7
                    select num;
    
                int numCount2 = numbersQuery.Count();

      对查询子句的结果使用方法语法。 只需将查询表达式括在括号内,然后应用点运算符并调用此方法。

      通常更好的做法是使用另一个变量(numCount2)来存储方法调用的结果。 这样就不太容易将查询本身与查询结果相混淆。

    从方法中返回查询

      任何查询的类型都必须为 IEnumerable 或 IEnumerable<T>,或一种派生类型(如 IQueryable<T>)。 因此,返回查询的方法的任何返回值或 out 参数也必须具有该类型。

      如果某个方法将查询具体化为具体的 List<T> 或 Array 类型,则认为该方法在返回查询结果(而不是查询本身)。 仍然能够编写或修改从方法返回的查询变量。

              // QueryMethhod1 returns a query as its value.
                    IEnumerable<string> QueryMethod1(ref int[] ints)
                    {
                        var intsToStrings = from i in ints
                                            where i > 4
                                            select i.ToString();
                        return intsToStrings;
                    }
    
                    // QueryMethod2 returns a query as the value of parameter returnQ.
                    void QueryMethod2(ref int[] ints, out IEnumerable<string> returnQ)
                    {
                        var intsToStrings = from i in ints
                                            where i < 4
                                            select i.ToString();
                        returnQ = intsToStrings;
                    }

      查询基本上是一组有关如何检索和组织数据的指令。

      若要执行查询,需要调用它的 GetEnumerator 方法。 当您使用 foreach 循环来循环访问元素时,将执行此调用。

      若要计算查询和存储其结果,而不执行 foreach 循环,请对查询变量调用下列方法之一:

    • ToList<TSource>
    • ToArray<TSource>
    • ToDictionary<TSource, TKey, TElement>
    • ToLookup<TSource, TKey, TElement>

      建议在存储查询结果时,将返回的集合对象分配给一个新变量,如下:

          static List<int> numbers = new List<int>() { 1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
            static void Main()
            {
                IEnumerable<int> queryFactorsOfFour =
                    from num in numbers
                    where num % 4 == 0
                    select num;
    
                // Store the results in a new variable
                // without executing a foreach loop.
                List<int> factorsofFourList = queryFactorsOfFour.ToList();
            }    

    运行时动态指定谓词筛选器

    • 使用 Contains<TSource> 方法:
     var queryNames =
                    from student in students
                    let i = student.ID.ToString()
                    where ids.Contains(i)  //ids is method's parameter
                    select new { student.LastName, student.ID };
    
                foreach (var name in queryNames)
                {
                    Console.WriteLine("{0}: {1}", name.LastName, name.ID);
                }
    • 使用 switch 语句进行筛选
         static void QueryByYear(string level)
            {
                GradeLevel year = (GradeLevel)Convert.ToInt32(level);
                IEnumerable<Student> studentQuery = null;
                switch (year)
                {
                    case GradeLevel.FirstYear:
                        studentQuery = from student in students
                                       where student.Year == GradeLevel.FirstYear
                                       select student;
                        break;
                    case GradeLevel.SecondYear:
                        studentQuery = from student in students
                                       where student.Year == GradeLevel.SecondYear
                                       select student;
                        break;
                   ……
    
                    default:
                        break;
                }

    参考

      [1]MSDN,在C# 中编写 LINQ 查询

  • 相关阅读:
    都为你整理好了,5种Java 随机方式对比!你都知道吗?
    你不知道的,Java代码性能优化的 40+ 细节,赶快收藏!
    大厂技术总监,送给刚毕业和快要毕业的程序员——7点建议
    .NET Core 微服务学习与实践系列文章目录索引(2019版)
    ManagementEventWatcher throws ManagementException with call to Stop()
    postman工具的使用
    java实体类读取属性文件,并赋值
    使用idea创建springboot的maven项目
    手写Promise实现过程
    用Javascript制作随机星星效果图
  • 原文地址:https://www.cnblogs.com/ybtools/p/6524982.html
Copyright © 2011-2022 走看看