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

一、OrderBy操作符
OrderBy操作符用于對(duì)輸入序列中的元素進(jìn)行排序,排序基于一個(gè)委托方法的返回值順序。排序過(guò)程完成后,會(huì)返回一個(gè)類型為IOrderEnumerable<T>的集合對(duì)象。其中IOrderEnumerable<T>接口繼承自IEnumerable<T>接口。下面來(lái)看看OrderBy的定義:

從上面的截圖中可以看出,OrderBy是一個(gè)擴(kuò)展方法,只要實(shí)現(xiàn)了IEnumerable<T>接口的就可以使用OrderBy進(jìn)行排序。OrderBy共有兩個(gè)重載方法:第一個(gè)重載的參數(shù)是一個(gè)委托類型和一個(gè)實(shí)現(xiàn)了IComparer<T>接口的類型。第二個(gè)重載的參數(shù)是一個(gè)委托類型??纯聪旅娴氖纠?/p>
定義產(chǎn)品類:
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()方法里面調(diào)用:
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)
{
// 初始化數(shù)據(jù)
List<Products> listProduct = new List<Products>()
{
new Products(){Id=1,CategoryId=1, Name="C#高級(jí)編程第10版", Price=100.67,CreateTime=DateTime.Now},
new Products(){Id=2,CategoryId=1, Name="Redis開發(fā)和運(yùn)維", 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("方法語(yǔ)法");
// 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("查詢表達(dá)式");
// 2、查詢表達(dá)式,返回匿名類
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();
}
}
}結(jié)果:

從截圖中可以看出,集合按照CreateTime進(jìn)行升序排序。
在來(lái)看看第一個(gè)重載方法的實(shí)現(xiàn):
先定義PriceComparer類實(shí)現(xiàn)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()方法里面調(diào)用:
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)
{
// 初始化數(shù)據(jù)
List<Products> listProduct = new List<Products>()
{
new Products(){Id=1,CategoryId=1, Name="C#高級(jí)編程第10版", Price=100.67,CreateTime=DateTime.Now},
new Products(){Id=2,CategoryId=1, Name="Redis開發(fā)和運(yùn)維", 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("方法語(yǔ)法");
// 1、查詢方法,按照價(jià)格升序排序,返回匿名類
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();
}
}
}結(jié)果:

注意:orderby必須在select之前出現(xiàn),查詢表達(dá)式最后只可能出現(xiàn)select或者groupby。
二、OrderByDescending
OrderByDescending操作符的功能與OrderBy操作符基本相同,二者只是排序的方式不同。OrderBy是升序排序,而OrderByDescending則是降序排列。下面看看OrderByDescending的定義:

從方法定義中可以看出,OrderByDescending的方法重載和OrderBy的方法重載一致。來(lái)看下面的例子:
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)
{
// 初始化數(shù)據(jù)
List<Products> listProduct = new List<Products>()
{
new Products(){Id=1,CategoryId=1, Name="C#高級(jí)編程第10版", Price=100.67,CreateTime=DateTime.Now},
new Products(){Id=2,CategoryId=1, Name="Redis開發(fā)和運(yùn)維", 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的方法語(yǔ)法和查詢表達(dá)式寫法有些不同。
Console.WriteLine("方法語(yǔ)法");
// 1、查詢方法,按照時(shí)間降序排序,返回匿名類
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("查詢表達(dá)式");
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();
}
}
}結(jié)果:

從截圖中可以看出:輸出結(jié)果按照時(shí)間降序排序。在來(lái)看看另外一個(gè)重載方法的調(diào)用:
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)
{
// 初始化數(shù)據(jù)
List<Products> listProduct = new List<Products>()
{
new Products(){Id=1,CategoryId=1, Name="C#高級(jí)編程第10版", Price=100.67,CreateTime=DateTime.Now},
new Products(){Id=2,CategoryId=1, Name="Redis開發(fā)和運(yùn)維", 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("方法語(yǔ)法");
// 1、查詢方法,按照價(jià)格降序排序,返回匿名類
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();
}
}
}結(jié)果:

輸出結(jié)果也是按照時(shí)間降序排序。
三、ThenBy排序
ThenBy操作符可以對(duì)一個(gè)類型為IOrderedEnumerable<T>,(OrderBy和OrderByDesceding操作符的返回值類型)的序列再次按照特定的條件順序排序。ThenBy操作符實(shí)現(xiàn)按照次關(guān)鍵字對(duì)序列進(jìn)行升序排列。下面來(lái)看看ThenBy的定義:

從截圖中可以看出:ThenBy()方法擴(kuò)展的是IOrderedEnumerable<T>,因此ThenBy操作符長(zhǎng)常常跟在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)
{
// 初始化數(shù)據(jù)
List<Products> listProduct = new List<Products>()
{
new Products(){Id=1,CategoryId=1, Name="C#高級(jí)編程第10版", Price=100.67,CreateTime=DateTime.Now},
new Products(){Id=2,CategoryId=1, Name="Redis開發(fā)和運(yùn)維", 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="高等數(shù)學(xué)", Price=97,CreateTime=DateTime.Now.AddMonths(-1)}
};
// 注意:ThenBy()的方法語(yǔ)法和查詢表達(dá)式寫法有些不同。
Console.WriteLine("方法語(yǔ)法升序排序");
// 1、查詢方法,按照商品分類升序排序,如果商品分類相同在按照價(jià)格升序排序 返回匿名類
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("查詢表達(dá)式升序排序");
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("方法語(yǔ)法降序排序");
// 1、查詢方法,按照商品分類降序排序,如果商品分類相同在按照價(jià)格升序排序 返回匿名類
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("查詢表達(dá)式降序排序");
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();
}
}
}結(jié)果:

四、ThenByDescending
ThenByDescending操作符于ThenBy操作符非常類似,只是是按照降序排序,實(shí)現(xiàn)按照次關(guān)鍵字對(duì)序列進(jìn)行降序排列。來(lái)看看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)
{
// 初始化數(shù)據(jù)
List<Products> listProduct = new List<Products>()
{
new Products(){Id=1,CategoryId=1, Name="C#高級(jí)編程第10版", Price=100.67,CreateTime=DateTime.Now},
new Products(){Id=2,CategoryId=1, Name="Redis開發(fā)和運(yùn)維", 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="高等數(shù)學(xué)", Price=97,CreateTime=DateTime.Now.AddMonths(-1)}
};
// 注意:ThenByDescending()的方法語(yǔ)法和查詢表達(dá)式寫法有些不同。
Console.WriteLine("方法語(yǔ)法升序排序");
// 1、查詢方法,按照商品分類升序排序,如果商品分類相同在按照價(jià)格降序排序 返回匿名類
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("查詢表達(dá)式升序排序");
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("方法語(yǔ)法降序排序");
// 1、查詢方法,按照商品分類降序排序,如果商品分類相同在按照價(jià)格降序排序 返回匿名類
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("查詢表達(dá)式降序排序");
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();
}
}
}結(jié)果:

五、Reverse
Reverse操作符用于生成一個(gè)與輸入序列中元素相同,但元素排列順序相反的新序列。下面來(lái)看看Reverse()方法的定義:
public static IEnumerable<TSource> Reverse<TSource>(this IEnumerable<TSource> source)
從方法定義中可以看到,這個(gè)擴(kuò)展方法,不需要輸入?yún)?shù),返回一個(gè)新集合。需要注意的是,Reverse方法的返回值是void??聪旅娴睦樱?/p>
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();
}
}
}運(yùn)行效果:

到此這篇關(guān)于LINQ排序操作符的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#使用代碼實(shí)現(xiàn)春晚?yè)淇伺颇g(shù)
這篇文章主要為大家詳細(xì)介紹了C#如何使用代碼實(shí)現(xiàn)龍年春晚?yè)淇伺颇g(shù)(守歲共此時(shí)),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2024-02-02
C#中的modbus Tcp協(xié)議的數(shù)據(jù)抓取和使用解析
這篇文章主要介紹了C#中的modbus Tcp協(xié)議的數(shù)據(jù)抓取和使用解析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07
WPF自定義控件實(shí)現(xiàn)ItemsControl魚眼效果
這篇文章主要為大家詳細(xì)介紹了WPF如何通過(guò)自定義控件實(shí)現(xiàn)ItemsControl魚眼效果,文中的示例代碼講解詳細(xì),需要的可以參考一下2024-01-01
用C#實(shí)現(xiàn)啟動(dòng)另一程序的方法實(shí)例
一段實(shí)例代碼,程序的目的是使用C#實(shí)現(xiàn)啟動(dòng)另一程序的方法。技術(shù)總監(jiān)給出了我們這樣一個(gè)有效的啟動(dòng)程序的有效方法,現(xiàn)在和大家分享下2013-07-07
C#實(shí)現(xiàn)分治算法求解股票問(wèn)題
本文主要介紹了C#實(shí)現(xiàn)分治算法求解股票問(wèn)題,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04

