C#对集合进行排序

 更新时间:2022年03月10日 09:48:27   作者:.NET开发菜鸟  
这篇文章介绍了C#对集合进行排序的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

先来看看下面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#对集合进行排序的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • C#/VB.NET 给Excel添加、删除数字签名的方法

    C#/VB.NET 给Excel添加、删除数字签名的方法

    这篇文章主要介绍了C#/VB.NET 给Excel添加、删除数字签名的方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-11-11
  • C#使用foreach语句遍历队列(Queue)的方法

    C#使用foreach语句遍历队列(Queue)的方法

    这篇文章主要介绍了C#使用foreach语句遍历队列(Queue)的方法,涉及foreach语句的使用技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-04-04
  • unity实现贪吃蛇游戏

    unity实现贪吃蛇游戏

    这篇文章主要为大家详细介绍了unity实现贪吃蛇游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-04-04
  • opencvsharp瑕疵检测的实现示例

    opencvsharp瑕疵检测的实现示例

    本文主要介绍了opencvsharp瑕疵检测的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-05-05
  • c#使用htmlagilitypack解析html格式字符串

    c#使用htmlagilitypack解析html格式字符串

    这篇文章主要介绍了c#使用htmlagilitypack解析html格式字符串的示例,需要的朋友可以参考下
    2014-03-03
  • WPF在VisualTree上增加Visual

    WPF在VisualTree上增加Visual

    这篇文章介绍了WPF在VisualTree上增加Visual的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-06-06
  • c# 用Dictionary实现日志数据批量插入

    c# 用Dictionary实现日志数据批量插入

    这篇文章主要介绍了c# 用Dictionary实现日志数据批量插入的步骤,帮助大家更好的理解和使用c#中的Dictionary类,感兴趣的朋友可以了解下
    2021-02-02
  • C#计算矩阵的秩实例分析

    C#计算矩阵的秩实例分析

    这篇文章主要介绍了C#计算矩阵的秩实现方法,以实例形式较为详细的分析了C#计算矩阵秩的原理与实现技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-08-08
  • C#面向对象编程之猜拳游戏实现方法

    C#面向对象编程之猜拳游戏实现方法

    这篇文章主要介绍了C#面向对象编程之猜拳游戏实现方法,以一个完整的猜拳游戏为例讲述了C#面向对象程序设计的具体实现步骤,具有一定的学习与借鉴价值,需要的朋友可以参考下
    2014-11-11
  • C# Lambda 知识回顾

    C# Lambda 知识回顾

    本文主要介绍了C#中Lambda的相关知识。具有一定的参考价值,下面跟着小编一起来看下吧
    2017-01-01

最新评论