LINQ排序操作符用法

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();
        }
    }
}

运行效果:

到此这篇关于LINQ排序操作符的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • LINQ 标准查询操作符

    推荐大家下载本文的PDF进行阅读,可以方便的使用书签来阅读各个方法,而且代码中的关键字是高亮显示的.pdf版下载地址 http://www.jb51.net/books/24738.html 一.投影操作符 1. Select Select操作符对单个序列或集合中的值进行投影.下面的示例中使用select从序列中返回Employee表的所有列: 复制代码 代码如下: using (NorthwindDataContext db=new NorthwindDataContext()) { //查询

  • LINQ投影操作符Select与限制操作符where介绍

    一.什么是LINQ?它可以用来做什么 语言集成查询(Language Integrated Query,LINQ)是一系列标准查询操作符的集合,这些操作符几乎对每一种数据源的导航.过滤和执行操作都提供了底层的基本查询架构. LINQ可查询的数据源包括XML(可使用LINQ TO XML).关系数据(使用LINQ TO SQL,及先前的DLINQ).ADO.NET DataSet(使用LINQ TO DataSet),以及内存中的数据. 二.投影操作符:Select Select操作符对单个序列或

  • LINQ操作符SelectMany的用法

    SelectMany操作符提供了将多个from子句组合起来的功能,相当于数据库中的多表连接查询,它将每个对象的结果合并成单个序列. 示例: student类: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SelectMany操作符 { /// <summary> /// 学生类 /// &

  • LINQ排序操作符用法

    Linq中的排序操作符包括OrderBy.OrderByDescending.ThenBy.ThenByDescending和Reverse,提供了升序或者降序排序. 一.OrderBy操作符 OrderBy操作符用于对输入序列中的元素进行排序,排序基于一个委托方法的返回值顺序.排序过程完成后,会返回一个类型为IOrderEnumerable<T>的集合对象.其中IOrderEnumerable<T>接口继承自IEnumerable<T>接口.下面来看看OrderBy的

  • c#中LINQ的基本用法(二)

    目录 1.筛选 2.用索引筛选 3.类型筛选 4.复合的from子句 5.排序 6.分组 7.对嵌套的对象分组 8.内连接 9.左连接 10.组连接 11.集合操作 12.合并 13.分区 14.聚合操作符 15.转换操作符 16.生成操作符 本文主要介绍LINQ查询操作符 LINQ查询为最常用的操作符定义了一个声明语法.还有许多查询操作符可用于Enumerable类.下面的例子需要用到LINQ基础(一)(https://www.jb51.net/article/244208.htm)的一些代码

  • c#中LINQ的基本用法(三)

    一.并行LINQ System.Linq名称空间中包含的类ParallelEnumerable可以分解查询的工作,使其分布在多个线程上.尽管Enumerable类给IEnumerable<T>接口定义了扩展方法,但ParallelEnumerable类的大多数扩展方法是ParallerQuery<TSource>类的扩展.例如,AsParallel()方法,它扩展了IEnumerable<T>接口,返回ParallelQuery<T>类,所以正常的集合类可以

  • C#使用LINQ查询操作符实例代码(二)

    目录 六.连表操作符 1.内连接 2.左外连接(DefaultIfEmpty) 3.组连接 七.集合操作 八.分区操作符 1.Take(): 2.TakeWhile(): 3.Skip(): 4.SkipWhile(): 九.聚合操作符 1.Count: 返回集合项数. 2.LongCount:返回一个 System.Int64,表示序列中的元素的总数量. 3.Sum: 序列中的所有数字的和. 4.Min: 返回集合中的最小值. 5.Max: 返回集合中的最大值. 6.Average: 返回集合

  • C#使用LINQ查询操作符实例代码(一)

    目录 相关阅读 示例业务背景介绍 一.筛选操作符 结果: 1.索引器筛选 2.类型筛选OfType 二.投影操作符 1.Select 子句 结果: 相应的lambda表达式: 2.复合的From子句 三.let子句 四.排序操作符 使用ThenBy() 和 ThenByDescending() 方法继续排序进行二次排序 五.分组操作符 1.对嵌套的对象分组 2.多字段分组 3.分组后再每组里面仅取满足条件的行 相关阅读 C#使用LINQ查询操作符实例代码(一) C#使用LINQ查询操作符实例代码

  • ES6新特性之数组、Math和扩展操作符用法示例

    本文实例讲述了ES6新特性之数组.Math和扩展操作符用法.分享给大家供大家参考,具体如下: 一.Array Array对象增加了一些新的静态方法,Array原型上也增加了一些新方法. 1.Array.from 从类数组和可遍历对象中创建Array的实例 类数组对象包括:函数中的arguments.由document.getElementsByTagName()返回的nodeList对象.新增加的Map和Set数据结构. //in ES6中 类数组转换为数组的方法 let itemElement

  • Python原始字符串与Unicode字符串操作符用法实例分析

    本文实例讲述了Python原始字符串与Unicode字符串操作符用法.分享给大家供大家参考,具体如下: #coding=utf8 ''''' 在原始字符串里,所有的字符串都是直接按照字面的意思来使用, 没有转义特殊或不能打印的字符. 正则表达式是一些告诫搜索匹配方式的字符串, 通过是由代表字符.分组.匹配信息.变量名.字符类等的特殊符号组成. 在原始字符串紧靠第一个引号前,需要加上r或R字母,来表示该字符是原始字符串. 原始字符串和普通字符串有这几乎完全相同的语法. Unicode字符串操作符,

  • Python映射拆分操作符用法实例

    本文实例讲述了Python映射拆分操作符用法.分享给大家供大家参考.具体如下: name="jack" age=24 s="name is {name} and age is {age}".format(**locals()) print s 运行结果如下: name is jack and age is 24 希望本文所述对大家的Python程序设计有所帮助.

  • c#中LINQ的基本用法(一)

    LINQ(Language Integrated Query,语言集成查询),在C#语言中集成了查询语法,可以用相同的语法访问不同的数据源.LINQ提供了不同数据源的抽象层,所以可以使用相同的语法.这里主要介绍LINQ的核心原理和C#中支持C# LINQ查询的语言扩展. 1.语法 使用LINQ查询出来自巴西的所以世界冠军.这里可以使用List<T>类的FindAll()方法,但使用LINQ查询语法更简单 static void LINQQuery() { // var query = from

随机推荐