欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

LINQ排序操作符用法

 更新時間:2022年02月28日 11:46:39   作者:.NET開發(fā)菜鳥  
這篇文章介紹了LINQ排序操作符的用法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

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

一、OrderBy操作符

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

從上面的截圖中可以看出,OrderBy是一個擴(kuò)展方法,只要實(shí)現(xiàn)了IEnumerable<T>接口的就可以使用OrderBy進(jìn)行排序。OrderBy共有兩個重載方法:第一個重載的參數(shù)是一個委托類型和一個實(shí)現(xiàn)了IComparer<T>接口的類型。第二個重載的參數(shù)是一個委托類型??纯聪旅娴氖纠?/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#高級編程第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("方法語法");
            // 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)行升序排序。

在來看看第一個重載方法的實(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#高級編程第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("方法語法");
            // 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();
        }
    }
}

結(jié)果:

注意:orderby必須在select之前出現(xiàn),查詢表達(dá)式最后只可能出現(xiàn)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)
        {
            // 初始化數(shù)據(jù)
            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開發(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的方法語法和查詢表達(dá)式寫法有些不同。
            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("查詢表達(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é)果按照時間降序排序。在來看看另外一個重載方法的調(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#高級編程第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("方法語法");
            // 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();
        }
    }
}

結(jié)果:

輸出結(jié)果也是按照時間降序排序。

三、ThenBy排序

ThenBy操作符可以對一個類型為IOrderedEnumerable<T>,(OrderBy和OrderByDesceding操作符的返回值類型)的序列再次按照特定的條件順序排序。ThenBy操作符實(shí)現(xiàn)按照次關(guān)鍵字對序列進(jìn)行升序排列。下面來看看ThenBy的定義:

從截圖中可以看出:ThenBy()方法擴(kuò)展的是IOrderedEnumerable<T>,因此ThenBy操作符長常常跟在OrderBy和OrderByDesceding之后??聪旅娴氖纠?/p>

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#高級編程第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()的方法語法和查詢表達(dá)式寫法有些不同。
            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("查詢表達(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("方法語法降序排序");
            // 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("查詢表達(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)鍵字對序列進(jìn)行降序排列。來看看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#高級編程第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()的方法語法和查詢表達(dá)式寫法有些不同。
            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("查詢表達(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("方法語法降序排序");
            // 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("查詢表達(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操作符用于生成一個與輸入序列中元素相同,但元素排列順序相反的新序列。下面來看看Reverse()方法的定義:

public static IEnumerable<TSource> Reverse<TSource>(this IEnumerable<TSource> source)

從方法定義中可以看到,這個擴(kuò)展方法,不需要輸入?yún)?shù),返回一個新集合。需要注意的是,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排序操作符的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • C#使用代碼實(shí)現(xiàn)春晚撲克牌魔術(shù)

    C#使用代碼實(shí)現(xiàn)春晚撲克牌魔術(shù)

    這篇文章主要為大家詳細(xì)介紹了C#如何使用代碼實(shí)現(xiàn)龍年春晚撲克牌魔術(shù)(守歲共此時),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下
    2024-02-02
  • C#中的modbus Tcp協(xié)議的數(shù)據(jù)抓取和使用解析

    C#中的modbus Tcp協(xié)議的數(shù)據(jù)抓取和使用解析

    這篇文章主要介紹了C#中的modbus Tcp協(xié)議的數(shù)據(jù)抓取和使用解析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-07-07
  • WPF自定義控件實(shí)現(xiàn)ItemsControl魚眼效果

    WPF自定義控件實(shí)現(xiàn)ItemsControl魚眼效果

    這篇文章主要為大家詳細(xì)介紹了WPF如何通過自定義控件實(shí)現(xiàn)ItemsControl魚眼效果,文中的示例代碼講解詳細(xì),需要的可以參考一下
    2024-01-01
  • 用C#實(shí)現(xiàn)啟動另一程序的方法實(shí)例

    用C#實(shí)現(xiàn)啟動另一程序的方法實(shí)例

    一段實(shí)例代碼,程序的目的是使用C#實(shí)現(xiàn)啟動另一程序的方法。技術(shù)總監(jiān)給出了我們這樣一個有效的啟動程序的有效方法,現(xiàn)在和大家分享下
    2013-07-07
  • 詳解C#之事件

    詳解C#之事件

    這篇文章主要介紹了C#之事件的知識點(diǎn),文中代碼非常詳細(xì),幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以參考下
    2020-06-06
  • c# 實(shí)現(xiàn)位圖算法(BitMap)

    c# 實(shí)現(xiàn)位圖算法(BitMap)

    這篇文章主要介紹了c# 如何實(shí)現(xiàn)位圖算法(BitMap),文中講解非常細(xì)致,幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-07-07
  • 二叉樹的遍歷算法(詳細(xì)示例分析)

    二叉樹的遍歷算法(詳細(xì)示例分析)

    以下代碼是對二叉樹的遍歷算法進(jìn)行了分析介紹,需要的朋友可以參考下
    2013-05-05
  • c#開發(fā)cad預(yù)覽圖塊步驟詳解

    c#開發(fā)cad預(yù)覽圖塊步驟詳解

    在本篇文章里小編給大家分享了關(guān)于c#開發(fā)cad預(yù)覽圖塊步驟和相關(guān)知識點(diǎn),需要的朋友們學(xué)習(xí)下。
    2019-02-02
  • C#實(shí)現(xiàn)分治算法求解股票問題

    C#實(shí)現(xiàn)分治算法求解股票問題

    本文主要介紹了C#實(shí)現(xiàn)分治算法求解股票問題,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-04-04
  • C# 基于消息發(fā)布訂閱模型的示例(上)

    C# 基于消息發(fā)布訂閱模型的示例(上)

    這篇文章主要介紹了C# 基于消息發(fā)布訂閱模型的示例,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下
    2021-03-03

最新評論