广告
返回顶部
首页 > 资讯 > 后端开发 > 其他教程 >LINQ排序操作符用法
  • 666
分享到

LINQ排序操作符用法

2024-04-02 19:04:59 666人浏览 八月长安
摘要

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

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排序操作符的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持编程网。

--结束END--

本文标题: LINQ排序操作符用法

本文链接: https://www.lsjlt.com/news/140788.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • LINQ排序操作符用法
    Linq中的排序操作符包括OrderBy、OrderByDescending、ThenBy、ThenByDescending和Reverse,提供了升序或者降序排序。 一、Orde...
    99+
    2022-11-13
  • LINQ排序操作符怎么使用
    这篇文章主要介绍了LINQ排序操作符怎么使用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇LINQ排序操作符怎么使用文章都会有所收获,下面我们一起来看看吧。Linq中的排序操作符包括OrderBy、OrderB...
    99+
    2023-06-29
  • LINQ操作符SelectMany的用法
    SelectMany操作符提供了将多个from子句组合起来的功能,相当于数据库中的多表连接查询,它将每个对象的结果合并成单个序列。 示例: student类: using ...
    99+
    2022-11-13
  • linq中的转换操作符
    目录一、AsEnumerable操作符二、ToArray操作符三、ToDictionary操作符四、ToList操作符五、ToLookUp操作符六、Cast操作符这些转换操作符将集合...
    99+
    2022-11-13
  • linq中的聚合操作符
    目录一、Aggregate操作符二、Average操作符1、直接求基本类型集合的平均值2、求listProduct集合中价格的平均值三、Count操作符四、LongCount操作符五...
    99+
    2022-11-13
  • linq中的限定操作符
    限定操作符运算返回一个Boolean值,该值指示序列中是否有一些元素满足条件或者是否所有元素都满足条件。 一、All操作符 All方法用来确定是否序列中的所有元素都满足条件。看下面的...
    99+
    2022-11-13
  • linq中的元素操作符
    目录一、Fitst操作符二、FirstOrDefault操作符三、Last操作符四、LastOrDefault操作符五、ElementAt操作符六:ElementAtOrDefaul...
    99+
    2022-11-13
  • linq中的分区操作符
    Linq中的分区指的是在不重新排列元素的情况下,将输入序列划分为两部分,然后返回其中一个部分的操作。 一、Take操作符 Take(int n)表示将从序列的开头返回数量为n的连续元...
    99+
    2022-11-13
  • linq中的连接操作符
    linq中的连接操作符主要包括Join()和GroupJoin()两个。 一、Join()操作符 Join()操作符非常类似于T-SQL中的inner join,它将两个数据源进行连...
    99+
    2022-11-13
  • linq中的分组操作符
    分组是根据一个特定的值将序列中的元素进行分组。LINQ只包含一个分组操作符:GroupBy。GroupBy操作符类似于T-SQL语言中的Group By语句。来看看GroupBy的方...
    99+
    2022-11-13
  • linq中的串联操作符
    串联是一个将两个集合连接在一起的过程。在Linq中,这个过程通过Concat操作符实现。Concat操作符用于连接两个集合,生成一个新的集合。来看看Concat操作符的定义: pub...
    99+
    2022-11-13
  • Linq 中如何使用Contains操作符
    Linq 中如何使用Contains操作符,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。投影和排序您可能还注意到我在之前的示例中暗藏了一个投影。在使用 Max 操作符之前,LI...
    99+
    2023-06-17
  • linq中聚合操作符怎么用
    这篇文章给大家分享的是有关linq中聚合操作符怎么用的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。一、Aggregate操作符Aggregate操作符对集合值执行自定义聚合运算。来看看Aggregate的定义:p...
    99+
    2023-06-29
  • LINQ教程之LINQ操作语法
    LINQ查询时有两种语法可供选择:查询表达式语法(Query Expression)和方法语法(Fluent Syntax)。 一、查询表达式语法 查询表达式语法是一种更接近SQL语...
    99+
    2022-11-13
  • C#如何使用LINQ查询操作符
    这篇文章主要讲解了“C#如何使用LINQ查询操作符”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C#如何使用LINQ查询操作符”吧!连表操作符1、内连接使用 join 子句 根据特定的条件合...
    99+
    2023-07-02
  • linq中的限定操作符怎么用
    本篇内容介绍了“linq中的限定操作符怎么用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!限定操作符运算返回一个Boolean值,该值指示序...
    99+
    2023-06-29
  • LINQ投影操作符Select与限制操作符where介绍
    一、什么是LINQ它可以用来做什么 语言集成查询(Language Integrated Query,LINQ)是一系列标准查询操作符的集合,这些操作符几乎对每一种数据源的导航、过滤...
    99+
    2022-11-13
  • LINQ中有哪些查询操作符
    这篇文章给大家介绍LINQ中有哪些查询操作符,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。操作符和LINQLINQ自身功能非常强大,无论使用的是LINQto XML、LINQto DataSets、LINQto Ent...
    99+
    2023-06-17
  • oracle排序操作
    查询排序最多的SQL语句:WITH sql_workarea AS (SELECT sql_id || '_' || child_number sql_id_child, &nb...
    99+
    2022-10-18
  • PHP 排序函数使用方法,按照字母排序等操作
    详解PHP排序方法使用 一、sort() 函数 用于对数组单元从低到高进行排序。 //数组$data = array('D','F','A','C','B');//排序sort($data);//输出排版标签echo "";//打印数据p...
    99+
    2023-10-20
    php 开发语言
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作