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

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

服务器之家 - 编程语言 - C# - C#对集合进行排序

C#对集合进行排序

2023-02-20 16:42.NET开发菜鸟 C#

这篇文章介绍了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();
        }
    }
}

输出结果:

C#对集合进行排序

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

C#对集合进行排序

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

 结果:

C#对集合进行排序

在按照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#对集合进行排序的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

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

延伸 · 阅读

精彩推荐
  • C#c# BackgroundWorker使用方法

    c# BackgroundWorker使用方法

    这篇文章主要介绍了c# BackgroundWorker使用方法,文中代码非常详细,帮助大家更好的参考学习,感兴趣的朋友可以了解下...

    风情单车5992022-09-09
  • C#详解c#与js的rsa加密互通

    详解c#与js的rsa加密互通

    这篇文章主要介绍了详解c#与js的rsa加密互通,帮助大家更好的理解和学习使用c#,感兴趣的朋友可以了解下...

    code2roc5122022-11-09
  • C#C#和lua相互调用的方法教程

    C#和lua相互调用的方法教程

    lua是一种脚本语言,可以方便的移植到各种宿主语言中,并且可以支持热更新,在游戏开发中也能当做主要的语言来编写游戏的逻辑,所以这篇文章主要给...

    Mr.小Y5112022-01-25
  • C#C#实现给Word每一页设置不同图片水印

    C#实现给Word每一页设置不同图片水印

    Word中设置水印时,可加载图片设置为水印效果,但通常添加水印效果时,会对所有页面都设置成统一效果。本文将利用C#实现给Word每一页设置不同图片水印...

    E-iceblue9972023-02-09
  • C#C#使用Datatable导出Excel

    C#使用Datatable导出Excel

    这篇文章主要为大家详细介绍了C#使用Datatable导出Excel的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    薛定谔家的猫6482022-03-01
  • C#VSCode配置C#运行环境的完整步骤

    VSCode配置C#运行环境的完整步骤

    这篇文章主要给大家介绍了关于VSCode配置C#运行环境的完整步骤,文中通过图文介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的...

    若尘8602022-10-10
  • C#C# TreeView无限目录树实现方法

    C# TreeView无限目录树实现方法

    这篇文章主要介绍了C# TreeView无限目录树实现方法,实例分析了TreeView节点操作的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...

    smartsmile20126212021-11-26
  • C#C# 总结QueueUserWorkItem传参几种方式案例详解

    C# 总结QueueUserWorkItem传参几种方式案例详解

    这篇文章主要介绍了C# 总结QueueUserWorkItem传参几种方式案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以...

    weixin_337691254292022-12-02