泛型的排序问题

 在实际应用中,遇到需要对泛型集合进行排序,感觉有点意思,给大家分享下。(代码粘贴到工程中改个namespace就可以用了)

VB.NET示例

HTML源码:

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="ListSort.aspx.vb" Inherits="Saas.Demo.Report.ListSort" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:DropDownList ID="CBOsortproperty" runat="server">
            <asp:ListItem Selected="True" Text="Birth" Value="2"></asp:ListItem>
            <asp:ListItem Text="ID" Value="0"></asp:ListItem>
            <asp:ListItem Text="Name" Value="1"></asp:ListItem>
        </asp:DropDownList>
        <asp:DropDownList ID="CBOsortorder" runat="server">
            <asp:ListItem Selected="True" Text="降序" Value="1"></asp:ListItem>
            <asp:ListItem Text="升序" Value="0"></asp:ListItem>
        </asp:DropDownList>
        <div>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
                <Columns>
                    <asp:BoundField DataField="ID" HeaderText="ID" />
                    <asp:BoundField DataField="Name" HeaderText="Name" />
                    <asp:BoundField DataField="Birth" HeaderText="Birth" />
                </Columns>
            </asp:GridView>
        </div>
        <asp:Button ID="Button1" runat="server" Text="排序" />
        <asp:Button ID="Button2" runat="server" Text="恢复" />
    </form>
</body>
</html>

Code Behind:

Imports System.Collections

Partial Public Class ListSort
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim lst As New List(Of Info)
        lst.Add(New Info(1, "Tim", "1975-11-20"))
        lst.Add(New Info(3, "Bob", "1978-11-20"))
        lst.Add(New Info(2, "Ben", "2005-11-20"))
        lst.Add(New Info(5, "Alston", "1995-11-20"))
        lst.Add(New Info(4, "Thoms", "2001-11-20"))

        Me.GridView1.DataSource = lst
        Me.GridView1.DataBind()
    End Sub
    ''' <summary>
    ''' 排序
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim lst As New List(Of Info)
        lst.Add(New Info(1, "Tim", "1975-11-20"))
        lst.Add(New Info(3, "Bob", "1978-11-20"))
        lst.Add(New Info(2, "Ben", "2005-11-20"))
        lst.Add(New Info(5, "Alston", "1995-11-20"))
        lst.Add(New Info(4, "Thoms", "2001-11-20"))

        Dim c As CompareType
        Select Case CBOsortproperty.SelectedValue
            Case "2"
                c = New CompareType(CompareType.CompareType.Birth)
            Case "0"
                c = New CompareType(CompareType.CompareType.ID)
            Case "1"
                c = New CompareType(CompareType.CompareType.Name)
            Case Else
                c = New CompareType(CompareType.CompareType.Birth)
        End Select

        lst.Sort(c)
        If CBOsortorder.SelectedValue.Equals("1") Then
            lst.Reverse()
        End If
        Me.GridView1.DataSource = lst
        Me.GridView1.DataBind()
    End Sub
    ''' <summary>
    ''' 恢复
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim lst As New List(Of Info)
        lst.Add(New Info(1, "Tim", "1975-11-20"))
        lst.Add(New Info(3, "Bob", "1978-11-20"))
        lst.Add(New Info(2, "Ben", "2005-11-20"))
        lst.Add(New Info(5, "Alston", "1995-11-20"))
        lst.Add(New Info(4, "Thoms", "2001-11-20"))

        Me.GridView1.DataSource = lst
        Me.GridView1.DataBind()
    End Sub
    Public Class Info
        Public Sub New(ByVal i As Integer, ByVal n As String, ByVal b As DateTime)
            Me.ID = i
            Me.Name = n
            Me.Birth = b
        End Sub

        Private _id As Integer
        Private _name As String
        Private _birth As DateTime

        Public Property ID() As Integer
            Get
                Return _id
            End Get
            Set(ByVal value As Integer)
                _id = value
            End Set
        End Property
        Public Property Name() As String
            Get
                Return _name
            End Get
            Set(ByVal value As String)
                _name = value
            End Set
        End Property
        Public Property Birth() As DateTime
            Get
                Return _birth
            End Get
            Set(ByVal value As DateTime)
                _birth = value
            End Set
        End Property
        ''' <summary>
        ''' 按指定属性比较的函数
        ''' </summary>
        ''' <param name="x">比较对象</param>
        ''' <param name="y">比较对象</param>
        ''' <param name="type">属性</param>
        ''' <returns>1:x>y;0:x=y;-1:y>x</returns>
        ''' <remarks>静态函数Shared Shadows Function</remarks>
        Public Shared Shadows Function CompareByType(ByVal x As Info, ByVal y As Info, ByVal type As CompareType.CompareType) As Integer
            Select Case type
                Case CompareType.CompareType.ID
                    Return x.ID.CompareTo(y.ID)
                Case CompareType.CompareType.Name
                    Return x.Name.CompareTo(y.Name)
                Case CompareType.CompareType.Birth
                    Return x.Birth.CompareTo(y.Birth)
            End Select
        End Function
    End Class

    Class CompareType
        Implements IComparer(Of Info)   '继承比较器接口IComparer

        Public Sub New()
            Me.ComType = CompareType.Birth
        End Sub
        Public Sub New(ByVal ct As CompareType)
            Me.ComType = ct
        End Sub

        Public Enum CompareType
            ID
            Name
            Birth
        End Enum

        Private _comType As CompareType

        Public Property ComType() As CompareType
            Get
                Return _comType
            End Get
            Set(ByVal value As CompareType)
                _comType = value
            End Set
        End Property
        ''' <summary>
        ''' 设定排序属性
        ''' </summary>
        ''' <param name="ct"></param>
        ''' <remarks></remarks>
        Public Sub SetCompareType(ByVal ct As CompareType)
            Me.ComType = ct
        End Sub
        ''' <summary>
        ''' 比较函数
        ''' </summary>
        ''' <param name="x">比较对象</param>
        ''' <param name="y">比较对象</param>
        ''' <returns>1:x>y;0:x=y;-1:y>x</returns>
        ''' <remarks>实现接口的Compare方法</remarks>
        Public Function Compare(ByVal x As Info, ByVal y As Info) As Integer Implements System.Collections.Generic.IComparer(Of Info).Compare
            If x Is Nothing Then
                If y Is Nothing Then
                    Return 0
                Else
                    Return -1
                End If
            ElseIf y Is Nothing Then
                Return 1
            Else
                Return Info.CompareByType(x, y, ComType)
            End If
        End Function
    End Class

End Class

C#.NET示例

HTML源码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ListSort.aspx.cs" Inherits="CSharpTest.ListSort" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>泛型排序</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:DropDownList ID="CBOsortproperty" runat="server">
            <asp:ListItem Selected="True" Text="Birthday" Value="2"></asp:ListItem>
            <asp:ListItem Text="ID" Value="0"></asp:ListItem>
            <asp:ListItem Text="Name" Value="1"></asp:ListItem>
        </asp:DropDownList>
        <asp:DropDownList ID="CBOsortorder" runat="server">
            <asp:ListItem Selected="True" Text="降序" Value="1"></asp:ListItem>
            <asp:ListItem Text="升序" Value="0"></asp:ListItem>
        </asp:DropDownList>
        <div>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
                <Columns>
                    <asp:BoundField DataField="ID" HeaderText="ID" />
                    <asp:BoundField DataField="Name" HeaderText="Name" />
                    <asp:BoundField DataField="Birthday" HeaderText="Birthday" />
                </Columns>
            </asp:GridView>
        </div>
        <asp:Button ID="Button1" runat="server" Text="排序" OnClick="Button1_Click" />
        <asp:Button ID="Button2" runat="server" Text="恢复" OnClick="Button2_Click" />
    </form>
</body>
</html>
Code Behind:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

namespace CSharpTest
{
    public partial class ListSort : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            GridView1.DataSource = InitList();
            GridView1.DataBind();
        }
        /// <summary>
        /// 初始化泛型集合
        /// </summary>
        /// <returns></returns>
        private List<Info> InitList()
        {
            List<Info> lst = new List<Info>();

            lst.Add(new Info(2, "T", "1985"));
            lst.Add(new Info(5, "B", "1856"));
            lst.Add(new Info(1, "A", "1997"));
            lst.Add(new Info(4, "Z", "2009"));
            lst.Add(new Info(3, "G", "2000"));

            return lst;
        }
        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e)
        {
            List<Info> lst = InitList();

            //创建比较器实例
            CompareType c;
            switch (CBOsortproperty.SelectedValue)
            {
                case "0":
                    c = new CompareType(CompareType.CompType.ID);
                    break;
                case "1":
                    c = new CompareType(CompareType.CompType.Name);
                    break;
                case "2":
                    c = new CompareType(CompareType.CompType.Birthday);
                    break;
                default:
                    c = new CompareType(CompareType.CompType.Birthday);
                    break;
            }
            lst.Sort(c);

            if (CBOsortorder.SelectedValue.Equals("1"))
            {
                lst.Reverse();  //泛型排序默认为升序,若要求降序排序,需调用此方法
            }

            GridView1.DataSource = lst;
            GridView1.DataBind();
        }
        /// <summary>
        /// 恢复
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button2_Click(object sender, EventArgs e)
        {
            GridView1.DataSource = InitList();
            GridView1.DataBind();
        }
    }

    public class Info
    {
        //构造函数
        public Info(int i,string n,string b)
        {
            ID = i;
            Name = n;
            Birthday = b;
        }
        //Property
        private int _ID;
        public int ID
        {
            get { return _ID; }
            set { _ID = value; }
        }
        private string _Name;
        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }
        private string _Birthday;
        public string Birthday
        {
            get { return _Birthday; }
            set { _Birthday = value; }
        }
        /// <summary>
        /// 静态函数,实现比较功能,便于在类CompareType中调用
        /// </summary>
        /// <param name="x">比较对象</param>
        /// <param name="y">比较对象</param>
        /// <param name="type">排序属性(枚举类型)</param>
        /// <returns>1:x>y;0:x==y;-1:y>x</returns>
        public static int CompareByType(Info x,Info y,CompareType.CompType type)
        {
            switch (type)
            {
                case CompareType.CompType.ID:
                    return x.ID.CompareTo(y.ID);
                case CompareType.CompType.Name:
                    return x.Name.CompareTo(y.Name);
                case CompareType.CompType.Birthday:
                    return x.Birthday.CompareTo(y.Birthday);
                default:
                    return 0;
            }
        }
    }
    /// <summary>
    /// 实现比较器接口IComparer
    /// </summary>
    public class CompareType:IComparer<Info>
    {
        public CompareType()
        {
            ComType = CompareType.CompType.Birthday;
        }

        public CompareType(CompType c)
        {
            ComType = c;
        }

        public enum CompType
        {
            ID,
            Name,
            Birthday
        }

        private CompType _ComType;

        public CompType ComType
        {
            get { return _ComType; }
            set { _ComType = value; }
        }
        /// <summary>
        /// 实现IComparer.Compare()
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public int Compare(Info x, Info y)
        {
            if (x == null)
            {
                if (y == null)
                {
                    return 0;
                }
                else
                {
                    return -1;
                }
            }
            else if (y == null)
            {
                return 1;
            }
            else
            {
                return Info.CompareByType(x,y,ComType); //调用类Info的静态函数CompareByType
            }
        }       
    }
}

原文地址:https://www.cnblogs.com/guoxiaowen/p/1383258.html