服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - LINQ排序操作符用法

LINQ排序操作符用法

2023-02-16 14:45.NET开发菜鸟 C#

这篇文章介绍了LINQ排序操作符的用法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

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

LINQ排序操作符用法

一、OrderBy操作符

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

LINQ排序操作符用法

从上面的截图中可以看出,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();
        }
    }
}

结果:

LINQ排序操作符用法

从截图中可以看出,集合按照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();
        }
    }
}

结果:

LINQ排序操作符用法

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

二、OrderByDescending

OrderByDescending操作符的功能与OrderBy操作符基本相同,二者只是排序的方式不同。OrderBy是升序排序,而OrderByDescending则是降序排列。下面看看OrderByDescending的定义:

LINQ排序操作符用法

从方法定义中可以看出,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();
        }
    }
}

结果:

LINQ排序操作符用法

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

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

结果:

LINQ排序操作符用法

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

三、ThenBy排序

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

LINQ排序操作符用法

从截图中可以看出: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();
        }
    }
}

结果:

LINQ排序操作符用法

四、ThenByDescending

ThenByDescending操作符于ThenBy操作符非常类似,只是是按照降序排序,实现按照次关键字对序列进行降序排列。来看看ThenByDescending的定义:

LINQ排序操作符用法

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

结果:

LINQ排序操作符用法

五、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排序操作符用法

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

原文地址:https://www.cnblogs.com/dotnet261010/p/6850936.html

延伸 · 阅读

精彩推荐
  • C#C#多线程中的异常处理操作示例

    C#多线程中的异常处理操作示例

    这篇文章主要介绍了C#多线程中的异常处理操作,涉及C#多线程及异常的捕获、处理等相关操作技巧,需要的朋友可以参考下...

    行走即歌3952022-07-21
  • C#Unity实现喷漆效果

    Unity实现喷漆效果

    这篇文章主要为大家详细介绍了Unity实现喷漆效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    无迹浪子10692022-09-23
  • C#C# winForm自定义弹出页面效果

    C# winForm自定义弹出页面效果

    这篇文章主要为大家详细介绍了C# winForm自定义弹出页面效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    铃铛当当11182022-12-26
  • C#Unity调取移动端的麦克风进行录音并播放

    Unity调取移动端的麦克风进行录音并播放

    这篇文章主要为大家详细介绍了Unity调取移动端的麦克风进行录音并播放,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参...

    幻世界5862022-07-27
  • C#Directory文件类的实例讲解

    Directory文件类的实例讲解

    下面小编就为大家分享一篇Directory文件类的实例讲解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    happy多乐4182022-02-12
  • C#C#异步迭代IAsyncEnumerable应用实现

    C#异步迭代IAsyncEnumerable应用实现

    IAsyncEnumerable可以来实现异步迭代,本文就主要介绍了C#异步迭代IAsyncEnumerable应用实现,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    鲁广广10512022-11-23
  • C#Unity 从Resources中动态加载Sprite图片的操作

    Unity 从Resources中动态加载Sprite图片的操作

    这篇文章主要介绍了Unity 从Resources中动态加载Sprite图片的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    爱尚游Bin10172022-11-11
  • C#Unity实现物体左右移动效果

    Unity实现物体左右移动效果

    这篇文章主要为大家详细介绍了Unity实现物体左右移动效果,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    _April_10772022-08-03