• C# Linq


    linq可以对多种数据源和对象进行查询,可以减少代码量,提高检索效率。

    感觉linq很像sql。。,但是语句的顺序不同

    linq的查询形式如下:

      from...

      select...

      where...

    例如查询偶数:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace linq
    {
        class Program
        {
            static void Main(string[] args)
            {
                // The Three Parts of a LINQ Query:
                //  1. Data source.
                int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
    
                // 2. Query creation.
                // numQuery is an IEnumerable<int>
                var numQuery =
                    from num in numbers
                    where (num % 2) == 0
                    select num;
    
                // 3. Query execution.
                foreach (int num in numQuery)
                {
                    Console.Write("{0} ", num);
                }
            }
        }
    }

    结果:0 2 4 6 请按任意键继续. . .

    where语句可以使用&&和||:

    var numQuery =
                    from num in numbers
                    where (num % 2) == 0&&(num%4)!=0
                    select num;

    结果为:

    2 6 请按任意键继续. . .

    var numQuery =
                    from num in numbers
                    where (num % 2) == 0||(num%3)==0
                    select num;


    结果为:

    0 2 3 4 6 请按任意键继续. . .

    linq里的其他关键字:

    orderby

    var queryLondonCustomers3 = 
        from cust in customers
        where cust.City == "London"
        orderby cust.Name ascending
        select cust;

    使用orderby…descending 可以相反顺序(从 Z 到 A)对结果进行排序
    group ... by ...

    // queryCustomersByCity is an IEnumerable<IGrouping<string, Customer>>
      var queryCustomersByCity =
          from cust in customers
          group cust by cust.City;
    
      // customerGroup is an IGrouping<string, Customer>
      foreach (var customerGroup in queryCustomersByCity)
      {
          Console.WriteLine(customerGroup.Key);
          foreach (Customer customer in customerGroup)
          {
              Console.WriteLine("    {0}", customer.Name);
          }
      }

    group ... by ...按指定的键分组结果

    join

    var innerJoinQuery =
        from cust in customers
        join dist in distributors on cust.City equals dist.City
        select new { CustomerName = cust.Name, DistributorName = dist.Name };

    联接运算创建数据源中没有显式建模的序列之间的关联。但在 LINQ 中,不必像在 SQL 中那样频繁使用 join,因为 LINQ 中的外键在对象模型中表示为包含项集合的属性。

  • 相关阅读:
    iOS基础教程:在建好的项目中加入CoreData[转]
    iOS开发--使用lipo命令制作模拟器与真机通用静态库
    Linux命令之du
    简单了解gzip、bzip2、xz
    Linux命令之rpm
    进入CentOS7紧急模式恢复root密码
    解决Linux用户模板文件被删除后显示不正常问题
    Linux修改用户基本信息(不含密码)
    Linux用户密码文件/etc/shadow相关
    SecureCRT、Xmanager对Linux上传下载文件或文件夹
  • 原文地址:https://www.cnblogs.com/wos1239/p/4465643.html
Copyright © 2020-2023  润新知