iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > 其他教程 >C#对集合进行排序
  • 171
分享到

C#对集合进行排序

2024-04-02 19:04:59 171人浏览 安东尼
摘要

先来看看下面List<T>泛型集合的排序例子: using System; using System.Collections.Generic; using System.

先来看看下面List<T>泛型集合排序例子:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CustomerSort
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> list = new List<int>();
            list.Add(1);
            list.Add(5);
            list.Add(2);
            list.Add(6);
            list.Add(3);
            list.Add(4);
            Console.WriteLine("*****排序前*****");
            foreach (var item in list)
            {
                Console.WriteLine(item.ToString());
            }

            list.Sort();
            Console.WriteLine("*****排序后*****");
            foreach (var item in list)
            {
                Console.WriteLine(item.ToString());
            }

            Console.ReadKey();
        }
    }
}

输出结果:

从上面的截图中可以看出,Sort()方法默认按照元素的大小进行从小到大的排序,为什么调用Sort()方法就能按照元素的大小进行从小到大的排序呢?其实现原理是什么呢?我们能不能自定义排序规则呢?带着这些问题,我们先来看看Sort()方法的定义,在Sort()方法上面按F12转到定义:

从截图中可以看出,Sort()方法使用了几个重载的方法。可以传递给它的参数有泛型委托Comparison<T> comparison和泛型接口IComparer<T> comparer,以及一个范围值和泛型接口IComparer<T> comparer。只有集合中的元素实现了IComparable<T>接口,才能使用不带参数的Sort()方法。我们在这里实现IComparer<T>接口来创建一个自定义类型的排序功能。

1、定义一个Student类,包括姓名和分数两个属性,可以按照姓名或分数进行排序,Student类定义如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CustomerSort
{
   public class Student
    {
        public string Name { get; set; }

        public double Score { get; set; }
    }
}

2、在定义一个枚举,表示排序的种类,即是按照Name排序还是按照Score排序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CustomerSort
{
    /// <summary>
    /// 排序的种类
    /// </summary>
   public enum CompareType
    {
        Name,
        Score
    }
}

3、实现IComparer接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CustomerSort
{
    /// <summary>
    /// StudentComparer自定义排序规则类实现IComparable接口
    /// </summary>
    public class StudentComparer : IComparer<Student>
    {
        private CompareType _compareType;

        /// <summary>
        /// 通过构造函数给_compareType赋值
        /// </summary>
        /// <param name="compareType"></param>
        public StudentComparer(CompareType compareType)
        {
            _compareType = compareType;
        }

        /// <summary>
        /// 实现IComparer接口的Compare
        /// </summary>
        /// <param name="other"></param>
        /// <returns></returns>
        public int Compare(Student x, Student y)
        {
            if (x == null && y == null)
            {
                return 0;
            }
            if (x == null)
            {
                return -1;
            }
            if (y == null)
            {
                return 1;
            }
            switch (_compareType)
            {
                case CompareType.Name:
                    return string.Compare(x.Name, y.Name);
                    break;
                case CompareType.Score:
                    return x.Score.CompareTo(y.Score);
                    break;
                default:
                    throw new ArgumentException("无效的比较类型");
            }
        }
    }
}

4、在Main()方法中调用:

先按照Name进行排序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CustomerSort
{
    class Program
    {
        static void Main(string[] args)
        {
            //List<int> list = new List<int>();
            //list.Add(1);
            //list.Add(5);
            //list.Add(2);
            //list.Add(6);
            //list.Add(3);
            //list.Add(4);
            //Console.WriteLine("*****排序前*****");
            //foreach (var item in list)
            //{
            //    Console.WriteLine(item.ToString());
            //}

            //list.Sort();
            //Console.WriteLine("*****排序后*****");
            //foreach (var item in list)
            //{
            //    Console.WriteLine(item.ToString());
            //}


            List<Student> list = new List<Student>()
            {
                new Student()
                {
                    Name="Tom",
                    Score=98
                } ,
                new Student()
                {
                    Name="Kevin",
                    Score=69
                } ,
                new Student()
                {
                    Name="Leo",
                    Score=81
                }
            };
            Console.WriteLine("*****排序前*****");
            foreach (var item in list)
            {
                Console.WriteLine(item.Name);
            }
            list.Sort(new StudentComparer(CompareType.Name));
            Console.WriteLine("*****排序后*****");
            foreach (var item in list)
            {
                Console.WriteLine(item.Name);
            }

            //Console.WriteLine("***按照Score排序***");

            Console.ReadKey();
        }
    }
}

 结果:

在按照Score进行排序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CustomerSort
{
    class Program
    {
        static void Main(string[] args)
        {
            //List<int> list = new List<int>();
            //list.Add(1);
            //list.Add(5);
            //list.Add(2);
            //list.Add(6);
            //list.Add(3);
            //list.Add(4);
            //Console.WriteLine("*****排序前*****");
            //foreach (var item in list)
            //{
            //    Console.WriteLine(item.ToString());
            //}

            //list.Sort();
            //Console.WriteLine("*****排序后*****");
            //foreach (var item in list)
            //{
            //    Console.WriteLine(item.ToString());
            //}


            List<Student> list = new List<Student>()
            {
                new Student()
                {
                    Name="Tom",
                    Score=98
                } ,
                new Student()
                {
                    Name="Kevin",
                    Score=69
                } ,
                new Student()
                {
                    Name="Leo",
                    Score=81
                }
            };
            //Console.WriteLine("*****排序前*****");
            //foreach (var item in list)
            //{
            //    Console.WriteLine(item.Name);
            //}
            //list.Sort(new StudentComparer(CompareType.Name));
            //Console.WriteLine("*****排序后*****");
            //foreach (var item in list)
            //{
            //    Console.WriteLine(item.Name);
            //}

            Console.WriteLine("*****排序前*****");
            foreach (var item in list)
            {
                Console.WriteLine(item.Score);
            }
            list.Sort(new StudentComparer(CompareType.Name));
            Console.WriteLine("*****排序后*****");
            foreach (var item in list)
            {
                Console.WriteLine(item.Score);
            }

            Console.ReadKey();
        }
    }
}

结果:

到此这篇关于C#对集合进行排序的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持编程网。

--结束END--

本文标题: C#对集合进行排序

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

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

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

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

下载Word文档
猜你喜欢
  • C#对集合进行排序
    先来看看下面List<T>泛型集合的排序例子: using System; using System.Collections.Generic; using System....
    99+
    2022-11-13
  • Java 中如何对集合进行排序
    Java 中如何对集合进行排序 在 Java 中,集合是一种非常常见的数据结构,它可以用来存储一组元素,而且可以动态地增加或删除元素。在实际的开发中,我们经常需要对集合中的元素进行排序,以便更方便地查...
    99+
    2023-09-25
    java 开发语言
  • 怎么在java中对集合进行排序
    这篇文章将为大家详细讲解有关怎么在java中对集合进行排序,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。常用的java框架有哪些1.SpringMVC,Spring Web MVC是一种基于...
    99+
    2023-06-14
  • 如何使用Collections.reverse对list集合进行降序排序
    目录使用Collections.reverse对list集合进行降序排序Collections.reverse原理使用Collections.reverse对list集合进行降序排序...
    99+
    2022-11-12
  • C#中对集合排序的三种方式
    对集合排序,可能最先想到的是使用OrderBy方法。 class Program { static void Main(string[] args) ...
    99+
    2022-11-13
  • java中怎么使用Collections.reverse对list集合进行降序排序
    这篇文章主要讲解了“java中怎么使用Collections.reverse对list集合进行降序排序”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“java中怎么使用Collections....
    99+
    2023-06-21
  • 使用Stream流对集合排序
    文章目录 0 写在前面1 格式1.1 介绍:1.2 单个属性排序格式:1.3 多个属性排序格式:1.4 注意事项 2 代码举例 0 写在前面 有一些业务需要对集合按照一些规则进行排序,...
    99+
    2023-09-11
    java 数据库 开发语言
  • java集合进行排序的方式总结
    ava集合的工具类Collections中提供了两种排序的方法,分别是: Collections.sort(List list) Collections.sort(...
    99+
    2022-11-12
  • 使用C中的列对ListView进行排序
    在C中使用List View进行排序的方法如下:1. 首先,定义一个callback函数来进行比较排序。该函数可以根据需要自定义比较...
    99+
    2023-09-07
    C
  • java使用lambda表达式对List对象集合的某个属性进行排序
    这里新建一个UserInfo对象,用来测试lambda表达式排序,属性如下:public class UserInfo { private int id; private int age; private Strin...
    99+
    2021-07-02
    java lambda List 对象集合 属性 排序
  • C#序列化与反序列化集合对象并进行版本控制
    当涉及到跨进程甚至是跨域传输数据的时候,我们需要把对象序列化和反序列化。 首先可以使用Serializable特性。 [Serializable] public cl...
    99+
    2022-11-13
  • Linux下如何对文件进行合并和排序
    这篇文章主要介绍了Linux下如何对文件进行合并和排序,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。在 Linux上对文件进行合并和排序的方法有很多,但使用哪种就取决于你想怎...
    99+
    2023-06-28
  • C语言对冒泡排序进行升级介绍
    目录一、补充一下关于void*指针的知识,易于我们对下列函数实现的理解二、实现排序函数中的核心,比较函数三、实现排序函数四、转换函数的实现总结简单的冒牌排序只能对一中数组的类型进行排...
    99+
    2022-11-13
  • Python中对list进行排序
    很多时候,我们需要对List进行排序,Python提供了两个方法对给定的List L进行排序,方法1.用List的成员函数sort进行排序方法2.用built-in函数sorted进行排序(从2.4开始)这两种方法使用起来差不多,以第一种为...
    99+
    2023-01-31
    中对 Python list
  • 怎么对Linux上的文件进行合并和排序
    这篇文章主要介绍了怎么对Linux上的文件进行合并和排序的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇怎么对Linux上的文件进行合并和排序文章都会有所收获,下面我们一起来看看吧。使用 cat如果你只想将一组文...
    99+
    2023-06-27
  • Java中使用Lambda表达式对集合排序
    文章目录 一.利用lambda对list集合排序1.升序排序2.降序排序对对象集合操作,其实与基本类型集合操作类似对 JSONArray 排序 二.java8-Lambda中比较器Comp...
    99+
    2023-09-11
    java 开发语言
  • 使用C#中的Array.Sort函数对数组进行排序
    标题:C#中使用Array.Sort函数对数组进行排序的示例正文:在C#中,数组是一种常用的数据结构,经常需要对数组进行排序操作。C#提供了Array类,其中有Sort方法可以方便地对数组进行排序。本文将演示如何使用C#中的Array.So...
    99+
    2023-11-18
    C# Array sort
  • MongoDB对指定键进行排序
    1.查看集合 show collections2.查看所有数据 db.runoob.find().pretty()3.通过view进行升序 db.runoob.find({'title':/...
    99+
    2022-10-18
  • java怎么对list进行排序
    Java中可以使用Collections.sort()方法对List进行排序。具体步骤如下:1. 导入java.util包中的Col...
    99+
    2023-09-14
    java
  • jquery中集合如何排序
    在jquery中对集合进行排序的方法:1.新建html项目,引入jquery;2.创建集合,并赋值;3.使用sort()函数对集合排序;具体步骤如下:首先,在新建一个html项目,在项目中引入jquery;<script type=&...
    99+
    2022-10-04
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作