c#之Linq

它是C# 3.0的新语法

(1)LINQ表达式以"from"开始,以"select 或 group by子句"结尾;

(2)LINQ表达式的输出是一个 IEnumerable<T> 或 IQueryable<T> 集合;(注:T 的类型 由 select 或 group by 推断出来)

基本查询

var getList = from b in personList
                          where b.Gender == true
                          select b;
            getList.ToList().ForEach(p => { Console.WriteLine(p.ToString()); });

加入排序

var getlistByoreder = from b in personList
                                  where b.Gender == true
                                  orderby b.ID descending
                                  select b;
            getlistByoreder.ToList().ForEach(p => { Console.WriteLine(p.ToString()); });

            Console.ReadLine();

连接查询

// Join连接查询
            Console.WriteLine("Join Query:");
            var joinedList = from p in personList
                             join c in childList
                             on p.ID equals c.ParentID
                             select new
                             {
                                 Person = p,
                                 Child = c
                             };
            foreach (var item in joinedList)
            {
                Console.WriteLine(item.ToString());
            }

总结:LINQ编译后会生成对应的标准查询运算符(查询->Where,排序->OrderBy,连接->Join,分组->GroupBy),所以LINQ表达式其实就是类似于SQL风格的一种更加友好语法糖而已。其本质还是扩展方法、泛型委托等“旧酒”,被一个“新瓶子”所包装了起来,就变得高大上了。

原文地址:https://www.cnblogs.com/ilooking/p/4137464.html