Linq中的排序操作符包括OrderBy、OrderByDescending、ThenBy、ThenByDescending和Reverse,提供了升序或者降序排序。

一、OrderBy操作符

OrderBy操作符用于对输入序列中的元素进行排序,排序基于一个委托方法的返回值顺序。排序过程完成后,会返回一个类型为IOrderEnumerable<T>的集合对象。其中IOrderEnumerable<T>接口继承自IEnumerable<T>接口。下面来看看OrderBy的定义:

从上面的截图中可以看出,OrderBy是一个扩展方法,只要实现了IEnumerable<T>接口的就可以使用OrderBy进行排序。OrderBy共有两个重载方法:第一个重载的参数是一个委托类型和一个实现了IComparer<T>接口的类型。第二个重载的参数是一个委托类型。看看下面的示例:

定义产品类:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace OrderOperation
{
public class Products
{
public int Id { get; set; }
public int CategoryId { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public DateTime CreateTime { get; set; }
}
}

在Main()方法里面调用:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace OrderOperation
{
class Program
{
static void Main(string[] args)
{
// 初始化数据
List<Products> listProduct = new List<Products>()
{
new Products(){Id=,CategoryId=, Name="C#高级编程第10版", Price=100.67,CreateTime=DateTime.Now},
new Products(){Id=,CategoryId=, Name="Redis开发和运维", Price=69.9,CreateTime=DateTime.Now.AddDays(-)},
new Products(){Id=,CategoryId=, Name="ASP.NET Core", Price=,CreateTime=DateTime.Now.AddMonths(-)},
new Products(){Id=,CategoryId=, Name="Entity Framework 6.x", Price=,CreateTime=DateTime.Now.AddMonths(-)}
};
Console.WriteLine("方法语法");
// 1、查询方法,返回匿名类
var list = listProduct.OrderBy(p => p.CreateTime).Select(p => new { id = p.Id, ProductName = p.Name,ProductPrice=p.Price,PublishTime=p.CreateTime }).ToList();
foreach (var item in list)
{
Console.WriteLine($"item:{item}");
}
Console.WriteLine("查询表达式");
// 2、查询表达式,返回匿名类
var listExpress = from p in listProduct orderby p.CreateTime select new { id = p.Id, ProductName = p.Name, ProductPrice = p.Price, PublishTime = p.CreateTime };
foreach (var item in listExpress)
{
Console.WriteLine($"item:{item}");
} Console.ReadKey();
}
}
}

结果:

从截图中可以看出,集合按照CreateTime进行升序排序。

在来看看第一个重载方法的实现:

先定义PriceComparer类实现IComparer<T>接口,PriceComparer类定义如下:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace OrderOperation
{
public class PriceComparer : IComparer<double>
{
public int Compare(double x, double y)
{
if (x > y)
{
return ; //表示x>y
}
else if (x < y)
{
return -; //表示x<y
}
else
{
return ; //表示x=y
}
}
}
}

在Main()方法里面调用:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace OrderOperation
{
class Program
{
static void Main(string[] args)
{
// 初始化数据
List<Products> listProduct = new List<Products>()
{
new Products(){Id=,CategoryId=, Name="C#高级编程第10版", Price=100.67,CreateTime=DateTime.Now},
new Products(){Id=,CategoryId=, Name="Redis开发和运维", Price=69.9,CreateTime=DateTime.Now.AddDays(-)},
new Products(){Id=,CategoryId=, Name="ASP.NET Core", Price=,CreateTime=DateTime.Now.AddMonths(-)},
new Products(){Id=,CategoryId=, Name="Entity Framework 6.x", Price=,CreateTime=DateTime.Now.AddMonths(-)}
};
Console.WriteLine("方法语法");
// 1、查询方法,按照价格升序排序,返回匿名类
var list = listProduct.OrderBy(p => p.Price,new PriceComparer()).Select(p => new { id = p.Id, ProductName = p.Name, ProductPrice = p.Price, PublishTime = p.CreateTime }).ToList();
foreach (var item in list)
{
Console.WriteLine($"item:{item}");
}
Console.ReadKey();
}
}
}

结果:

注意:orderby必须在select之前出现,查询表达式最后只可能出现select或者groupby。

二、OrderByDescending

OrderByDescending操作符的功能与OrderBy操作符基本相同,二者只是排序的方式不同。OrderBy是升序排序,而OrderByDescending则是降序排列。下面看看OrderByDescending的定义:
从方法定义中可以看出,OrderByDescending的方法重载和OrderBy的方法重载一致。来看下面的例子:
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace OrderOperation
{
class Program
{
static void Main(string[] args)
{
// 初始化数据
List<Products> listProduct = new List<Products>()
{
new Products(){Id=,CategoryId=, Name="C#高级编程第10版", Price=100.67,CreateTime=DateTime.Now},
new Products(){Id=,CategoryId=, Name="Redis开发和运维", Price=69.9,CreateTime=DateTime.Now.AddDays(-)},
new Products(){Id=,CategoryId=, Name="ASP.NET Core", Price=,CreateTime=DateTime.Now.AddMonths(-)},
new Products(){Id=,CategoryId=, Name="Entity Framework 6.x", Price=,CreateTime=DateTime.Now.AddMonths(-)}
};
// 注意:OrderByDescending的方法语法和查询表达式写法有些不同。
Console.WriteLine("方法语法");
// 1、查询方法,按照时间降序排序,返回匿名类
var list = listProduct.OrderByDescending(p => p.CreateTime).Select(p => new { id = p.Id, ProductName = p.Name, ProductPrice = p.Price, PublishTime = p.CreateTime }).ToList();
foreach (var item in list)
{
Console.WriteLine($"item:{item}");
}
Console.WriteLine("查询表达式");
var listExpress = from p in listProduct orderby p.CreateTime descending select new { id = p.Id, ProductName = p.Name, ProductPrice = p.Price, PublishTime = p.CreateTime };
foreach (var item in list)
{
Console.WriteLine($"item:{item}");
}
Console.ReadKey();
}
}
}

结果:

从截图中可以看出:输出结果按照时间降序排序。在来看看另外一个重载方法的调用:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace OrderOperation
{
class Program
{
static void Main(string[] args)
{
// 初始化数据
List<Products> listProduct = new List<Products>()
{
new Products(){Id=,CategoryId=, Name="C#高级编程第10版", Price=100.67,CreateTime=DateTime.Now},
new Products(){Id=,CategoryId=, Name="Redis开发和运维", Price=69.9,CreateTime=DateTime.Now.AddDays(-)},
new Products(){Id=,CategoryId=, Name="ASP.NET Core", Price=,CreateTime=DateTime.Now.AddMonths(-)},
new Products(){Id=,CategoryId=, Name="Entity Framework 6.x", Price=,CreateTime=DateTime.Now.AddMonths(-)}
};
Console.WriteLine("方法语法");
// 1、查询方法,按照价格降序排序,返回匿名类
var list = listProduct.OrderByDescending(p => p.Price, new PriceComparer()).Select(p => new { id = p.Id, ProductName = p.Name, ProductPrice = p.Price, PublishTime = p.CreateTime }).ToList();
foreach (var item in list)
{
Console.WriteLine($"item:{item}");
}
Console.ReadKey();
}
}
}

结果:

输出结果也是按照时间降序排序。

三、ThenBy排序

ThenBy操作符可以对一个类型为IOrderedEnumerable<T>,(OrderBy和OrderByDesceding操作符的返回值类型)的序列再次按照特定的条件顺序排序。ThenBy操作符实现按照次关键字对序列进行升序排列。下面来看看ThenBy的定义:

从截图中可以看出:ThenBy()方法扩展的是IOrderedEnumerable<T>,因此ThenBy操作符长常常跟在OrderBy和OrderByDesceding之后。看下面的示例:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace OrderOperation
{
class Program
{
static void Main(string[] args)
{
// 初始化数据
List<Products> listProduct = new List<Products>()
{
new Products(){Id=,CategoryId=, Name="C#高级编程第10版", Price=100.67,CreateTime=DateTime.Now},
new Products(){Id=,CategoryId=, Name="Redis开发和运维", Price=69.9,CreateTime=DateTime.Now.AddDays(-)},
new Products(){Id=,CategoryId=, Name="活着", Price=,CreateTime=DateTime.Now.AddMonths(-)},
new Products(){Id=,CategoryId=, Name="高等数学", Price=,CreateTime=DateTime.Now.AddMonths(-)}
};
// 注意:ThenBy()的方法语法和查询表达式写法有些不同。
Console.WriteLine("方法语法升序排序");
// 1、查询方法,按照商品分类升序排序,如果商品分类相同在按照价格升序排序 返回匿名类
var list = listProduct.OrderBy(p => p.CategoryId).ThenBy(p=>p.Price).Select(p => new { id = p.CategoryId, ProductName = p.Name, ProductPrice = p.Price, PublishTime = p.CreateTime }).ToList();
foreach (var item in list)
{
Console.WriteLine($"item:{item}");
}
Console.WriteLine("查询表达式升序排序");
var listExpress = from p in listProduct orderby p.CategoryId,p.Price select new { id = p.CategoryId, ProductName = p.Name, ProductPrice = p.Price, PublishTime = p.CreateTime };
foreach (var item in listExpress)
{
Console.WriteLine($"item:{item}");
}
Console.WriteLine("方法语法降序排序");
// 1、查询方法,按照商品分类降序排序,如果商品分类相同在按照价格升序排序 返回匿名类
var listDesc = listProduct.OrderByDescending(p => p.CategoryId).ThenBy(p => p.Price).Select(p => new { id = p.CategoryId, ProductName = p.Name, ProductPrice = p.Price, PublishTime = p.CreateTime }).ToList();
foreach (var item in listDesc)
{
Console.WriteLine($"item:{item}");
}
Console.WriteLine("查询表达式降序排序");
var listExpressDesc = from p in listProduct orderby p.CategoryId descending , p.Price select new { id = p.CategoryId, ProductName = p.Name, ProductPrice = p.Price, PublishTime = p.CreateTime };
foreach (var item in listExpressDesc)
{
Console.WriteLine($"item:{item}");
}
Console.ReadKey();
}
}
}

结果:

四、ThenByDescending

ThenByDescending操作符于ThenBy操作符非常类似,只是是按照降序排序,实现按照次关键字对序列进行降序排列。来看看ThenByDescending的定义:
从截图中可以看出:ThenByDescending()方法扩展的是IOrderedEnumerable<T>,因此ThenByDescending操作符也是常常跟在OrderBy和OrderByDesceding之后。看下面的例子:
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace OrderOperation
{
class Program
{
static void Main(string[] args)
{
// 初始化数据
List<Products> listProduct = new List<Products>()
{
new Products(){Id=,CategoryId=, Name="C#高级编程第10版", Price=100.67,CreateTime=DateTime.Now},
new Products(){Id=,CategoryId=, Name="Redis开发和运维", Price=69.9,CreateTime=DateTime.Now.AddDays(-)},
new Products(){Id=,CategoryId=, Name="活着", Price=,CreateTime=DateTime.Now.AddMonths(-)},
new Products(){Id=,CategoryId=, Name="高等数学", Price=,CreateTime=DateTime.Now.AddMonths(-)}
};
// 注意:ThenByDescending()的方法语法和查询表达式写法有些不同。
Console.WriteLine("方法语法升序排序");
// 1、查询方法,按照商品分类升序排序,如果商品分类相同在按照价格降序排序 返回匿名类
var list = listProduct.OrderBy(p => p.CategoryId).ThenByDescending(p => p.Price).Select(p => new { id = p.CategoryId, ProductName = p.Name, ProductPrice = p.Price, PublishTime = p.CreateTime }).ToList();
foreach (var item in list)
{
Console.WriteLine($"item:{item}");
}
Console.WriteLine("查询表达式升序排序");
var listExpress = from p in listProduct orderby p.CategoryId, p.Price descending select new { id = p.CategoryId, ProductName = p.Name, ProductPrice = p.Price, PublishTime = p.CreateTime };
foreach (var item in listExpress)
{
Console.WriteLine($"item:{item}");
}
Console.WriteLine("方法语法降序排序");
// 1、查询方法,按照商品分类降序排序,如果商品分类相同在按照价格降序排序 返回匿名类
var listDesc = listProduct.OrderByDescending(p => p.CategoryId).ThenByDescending(p => p.Price).Select(p => new { id = p.CategoryId, ProductName = p.Name, ProductPrice = p.Price, PublishTime = p.CreateTime }).ToList();
foreach (var item in listDesc)
{
Console.WriteLine($"item:{item}");
}
Console.WriteLine("查询表达式降序排序");
var listExpressDesc = from p in listProduct orderby p.CategoryId descending, p.Price descending select new { id = p.CategoryId, ProductName = p.Name, ProductPrice = p.Price, PublishTime = p.CreateTime };
foreach (var item in listExpressDesc)
{
Console.WriteLine($"item:{item}");
}
Console.ReadKey();
}
}
}

结果:

五、Reverse

Reverse操作符用于生成一个与输入序列中元素相同,但元素排列顺序相反的新序列。下面来看看Reverse()方法的定义:

 public static IEnumerable<TSource> Reverse<TSource>(this IEnumerable<TSource> source)

从方法定义中可以看到,这个扩展方法,不需要输入参数,返回一个新集合。需要注意的是,Reverse方法的返回值是void。看下面的例子:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace ThenBy
{
class Program
{
static void Main(string[] args)
{
string[] str = { "A", "B", "C", "D", "E"};
var query = str.Select(p => p).ToList();
query.Reverse();
foreach (var item in query)
{
Console.WriteLine(item);
} Console.ReadKey();
}
}
}

运行效果:

LINQ操作符四:排序操作符的更多相关文章

  1. LINQ系列:Linq to Object排序操作符

    LINQ排序操作符包括:OrderBy.OrderByDescending.ThenBy.ThenByDescending及Reverse. 1. OrderBy 1>. 原型定义 public ...

  2. C#编程(六十二)---------LINQ标准的查询操作符

    LINQ标准的查询操作符 首先我们来看一下LINQ的操作符,可根据查询操作符的操作”类型”进行分类,如把它们分成投影,限制,排序,联接,分组,串联,聚合,集合,生成,转换,元素,相等,量词,分割等. ...

  3. 转linq中的Single()、First()、Take(1) LINQ 标准的查询操作符 排序 orderby、thenby、Take

    Single():操作一个集合,同时强要求只有一个对象匹配,并返回这一个. First():操作一个集合,可以有多个对象匹配,但是只返回第一个. Take(1):操作一个集合,可以有对个对象匹配,单只 ...

  4. LINQ to Entity Framework 操作符(转)

    在开始了解LINQ to Entities之前,需要先对.NET Framework 3.5版本后对C#语言的几个扩展特性做一些阐释,这有助于我们更容易.更深刻的理解LINQ to Entities技 ...

  5. Linq 27个常用操作符说明

    1.Where 操作符用于限定输入集合中的元素,将符合条件的元素组织声称一个序列结果.2.Select  操作符用于根据输入序列中的元素创建相应的输出序列中的元素,输出序列中的元素类型可以与输入序列中 ...

  6. linq操作符:元素操作符

    元素操作符仅返回一个元素. 一.Fitst操作符 First操作符将返回序列中的第一个元素.如果序列中不包含任何元素,则First<T>方法将引发异常.来看看First()方法的定义: 从 ...

  7. 【Linq】标准查询操作符

    A.1 聚合 聚合操作符(见表A-1),所有的结果只有一个值而不是一个序列. Average 和 Sum 针对数值 (任何内置数值类型)序列或使用委托从元素值转换为内置数值类型的元素序列. Min 和 ...

  8. LINQ系列:Linq to Object集合操作符

    集合操作符对元素的集合或序列集合进行操作,并返回一个集合.LINQ共有4种集合查询操作符:Distinct.Union.Intersect和Except. 1. Distinct Distinct操作 ...

  9. linq操作符:连接操作符

    linq中的连接操作符主要包括Join()和GroupJoin()两个. 一.Join()操作符 Join()操作符非常类似于T-SQL中的inner join,它将两个数据源进行连接,根据两个数据源 ...

随机推荐

  1. PHP5.4新特性

    PHP5.4 此次更新的关键新特性,包括:新增traits,更精简的Array数组语法,供测试使用的内建webserver,可以闭包使用的$this指针,实例化类成员访问, PHP 5.4.0 性能大 ...

  2. Windows下面安装和配置Solr 4.9(三)支持中文分词器

    首先将下载解压后的solr-4.9.0的目录里面F:\tools\开发工具\Lucene\solr-4.9.0\contrib\analysis-extras\lucene-libs找到lucene- ...

  3. Oracle 11g的Deferred Segment Creation

    本篇主要介绍Oracle 11g中推出的“延迟段创建”(Deferred Segment Creation)特性,以及当我们使用这种特性时,需要注意的问题. 1)Deferred Segment Cr ...

  4. python学习笔记013——模块中的私有属性

    1 私有属性的使用方式 在python中,没有类似private之类的关键字来声明私有方法或属性.若要声明其私有属性,语法规则为: 属性前加双下划线,属性后不加(双)下划线,如将属性name私有化,则 ...

  5. python练习笔记——用函数对列表奇偶分类,且过程不增加新列表

    编写一个函数:函数接收一个列表,将列表中所有的奇数,放到偶数之前,要求过程中不增加新的列表 def fun(*args): # 因为奇数放在偶数之前,标记出奇数中的偶数 # 并将该偶数取出放在数列的最 ...

  6. RAC安装重新运行root.sh

    rac1执行root.sh成功,rac2执行失败. 在重新执行root.sh前,在rac2上把crs等配置信息删除: # /u01/app//grid/crs/install/rootcrs.pl - ...

  7. Linux中断 - IRQ number和中断描述符

    一.前言 本文主要围绕IRQ number和中断描述符(interrupt descriptor)这两个概念描述通用中断处理过程.第二章主要描述基本概念,包括什么是IRQ number,什么是中断描述 ...

  8. sqlserver把小数点后面多余的0去掉

    Sql中想把小数点后多余的0去掉,怎么办? select 5000/10000.0 --想变成0.5select 5500/10000.0 --想变成0.55select 5550/10000.0 - ...

  9. 深度学习图像标注工具VGG Image Annotator (VIA)使用教程

    VGG Image Annotator (VIA)是一款开源的图像标注工具,由Visual Geometry Group开发. 可以在线和离线使用,可标注矩形.圆.椭圆.多边形.点和线.标注完成后,可 ...

  10. 【Android】17.0 第17章 服务绑定—本章示例主界面

    分类:C#.Android.VS2015: 创建日期:2016-03-03 一.简介 通过服务绑定(Bound Services),可以轻松实现后台服务与界面(UI)的交互. 二.本章示例主界面 1. ...