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 中的外键在对象模型中表示为包含项集合的属性。

原文地址:https://www.cnblogs.com/wos1239/p/4465643.html