LINQ排序操作符用法
作者:.NET开发菜鸟 发布时间:2023-10-26 02:19:10
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=1,CategoryId=1, Name="C#高级编程第10版", Price=100.67,CreateTime=DateTime.Now},
new Products(){Id=2,CategoryId=1, Name="Redis开发和运维", Price=69.9,CreateTime=DateTime.Now.AddDays(-19)},
new Products(){Id=3,CategoryId=1, Name="ASP.NET Core", Price=57,CreateTime=DateTime.Now.AddMonths(-3)},
new Products(){Id=4,CategoryId=1, Name="Entity Framework 6.x", Price=97,CreateTime=DateTime.Now.AddMonths(-1)}
};
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 1; //表示x>y
}
else if (x < y)
{
return -1; //表示x<y
}
else
{
return 0; //表示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=1,CategoryId=1, Name="C#高级编程第10版", Price=100.67,CreateTime=DateTime.Now},
new Products(){Id=2,CategoryId=1, Name="Redis开发和运维", Price=69.9,CreateTime=DateTime.Now.AddDays(-19)},
new Products(){Id=3,CategoryId=1, Name="ASP.NET Core", Price=57,CreateTime=DateTime.Now.AddMonths(-3)},
new Products(){Id=4,CategoryId=1, Name="Entity Framework 6.x", Price=97,CreateTime=DateTime.Now.AddMonths(-1)}
};
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=1,CategoryId=1, Name="C#高级编程第10版", Price=100.67,CreateTime=DateTime.Now},
new Products(){Id=2,CategoryId=1, Name="Redis开发和运维", Price=69.9,CreateTime=DateTime.Now.AddDays(-19)},
new Products(){Id=3,CategoryId=1, Name="ASP.NET Core", Price=57,CreateTime=DateTime.Now.AddMonths(-3)},
new Products(){Id=4,CategoryId=1, Name="Entity Framework 6.x", Price=97,CreateTime=DateTime.Now.AddMonths(-1)}
};
// 注意: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=1,CategoryId=1, Name="C#高级编程第10版", Price=100.67,CreateTime=DateTime.Now},
new Products(){Id=2,CategoryId=1, Name="Redis开发和运维", Price=69.9,CreateTime=DateTime.Now.AddDays(-19)},
new Products(){Id=3,CategoryId=1, Name="ASP.NET Core", Price=57,CreateTime=DateTime.Now.AddMonths(-3)},
new Products(){Id=4,CategoryId=1, Name="Entity Framework 6.x", Price=97,CreateTime=DateTime.Now.AddMonths(-1)}
};
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=1,CategoryId=1, Name="C#高级编程第10版", Price=100.67,CreateTime=DateTime.Now},
new Products(){Id=2,CategoryId=1, Name="Redis开发和运维", Price=69.9,CreateTime=DateTime.Now.AddDays(-19)},
new Products(){Id=3,CategoryId=2, Name="活着", Price=57,CreateTime=DateTime.Now.AddMonths(-3)},
new Products(){Id=4,CategoryId=3, Name="高等数学", Price=97,CreateTime=DateTime.Now.AddMonths(-1)}
};
// 注意: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的定义:
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=1,CategoryId=1, Name="C#高级编程第10版", Price=100.67,CreateTime=DateTime.Now},
new Products(){Id=2,CategoryId=1, Name="Redis开发和运维", Price=69.9,CreateTime=DateTime.Now.AddDays(-19)},
new Products(){Id=3,CategoryId=2, Name="活着", Price=57,CreateTime=DateTime.Now.AddMonths(-3)},
new Products(){Id=4,CategoryId=3, Name="高等数学", Price=97,CreateTime=DateTime.Now.AddMonths(-1)}
};
// 注意: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();
}
}
}
运行效果:
来源:https://www.cnblogs.com/dotnet261010/p/6850936.html


猜你喜欢
- 简介使用配置类和注解代替web.xml和SpringMVC配置文件的功能在Servlet3.0环境中,容器会在类路径中查找实现javax.s
- 背景近年来,在并发算法领域的大多数研究都侧重于非阻塞算法,这种算法用底层的原子机器指令(例如比较并发交换指令)代替锁来确保数据在并发访问中的
- JavaWeb项目部署到服务器详细步骤本地准备在eclipse中将项目打成war文件:鼠标右键要部署到服务器上的项目导出项目数据库文件MyS
- 先看效果:输入内容,点击生成二维码:点击logo图案:代码:QRCodeUtil:package com.example.administr
- Ajax本质上和普通的HTTP请求是一样的,只不过普通的HTTP请求是给人看的,而Ajax请求是给JS代码去用的。所以Ajax请求的页面一般
- C#连接本地.mdf文件:项目中右键点击,新增——数据——基于服务的数据库,项目下直接生成.mdf数据库文件,后台(数据库的写入用参数传递)
- 前言DataGridView是开发Winform的一个列表展示,类似于表格。学会下面的基本特征用法,再辅以经验,基本功能开发没问题。基本的数
- 特简单, 没有数据库, 还没有处理各种异常。登录:输入用户名点击的登录即可。发送消息: 特定格式->toUser:message1.
- Java中对象与C++中对象的放置安排的对比概要:Java中,所有的对象都存放在堆(Heap,一种通用的内存池)中;而对象的引用是存放在堆栈
- 前言最近做了一个调查问卷导出的功能,需求是将维护的题目,答案,导出成word,参考了几种方案之后,选择功能强大的freemarker+固定格
- 在编写程序,我们经常会对一些时间进行比较,比如要搜寻一个时间范围中的数据,需要用户输入开始时间和结束时间,如果结束时间小于或等于开始时间,那
- 调用示例: 执行效果: 2.实现代码:/// <summary> 2 &
- 快到过农历年了,微信红包也越来越多了,出现了好多红包 * 程序,就很好奇如何实现的,于是自己研究了一番,亲自写了个微信抢红包的APP。现在就一
- 目录一、为什么用DiskLruCache1、LruCache和DiskLruCache2、为何使用DiskLruCache二、DiskLru
- 一、前言之前介绍了JMeter engine启动原理,但是里面涉及到HashTree这个类结构没有给大家详细介绍,这边文章就详细介绍JMet
- 一、什么是Websocket?1.WebSocket是HTML5下一种新的协议(websocket协议本质上是一个基于tcp的协议)2.它实
- Zookeeper和Eureka哪个更好?1、CAP理论一个分布式系统不可能同时很好的满足一致性,可用性和分区容错性这三个需求C:数据一致性
- 众所周知,在墙内开发很头疼的一件事就是Maven仓库的连接速度太慢。虽然对于很多互联网企业和大中型软件公司,建个镜像是分分钟的事。但对于个人
- 1.类的6个默认成员函数默认成员函数:用户没有显示实现,编译器会生成的成员函数称为默认成员函数。如果一个类中什么成员都没有,简称为空类。但空
- 这几年一直在做手机上和电视盒的App,几乎没有考虑过横竖屏切换的问题。电视盒好说,横屏不变,你要是给它设计个竖屏人家也没机会使;而手机上的应