C#利用iComparable接口实现List排序

时间:2021-04-14 15:08:22

List<T>类可以使用Sort()方法对元素排序。

Sort()方法定义了几个重载方法,分别是
  public void List<T>.Sort(),不带有任何参数的Sort方法
  public void List<T>.Sort(Comparison<T>),带有比较代理方法参数的Sort方法  
  public void List<T>.Sort(IComparer<T>), 带有比较器参数的Sort方法 
  public void List<T>.Sort(Int32,Int32,IComparer<T>),带有比较起参数,可以指定排序范围的Sort方法

第一种方法必须继承IComparable<>接口,下面是示例代码:

// <copyright file="ServiceOfferingContent.cs" company="Deloitte">
// Copyright (c) Deloitte. All rights reserved.
// </copyright>
// <author>Haibin Chen</author>
// <email>Claudchen@Deloitte.com.cn</email>
// <date>2016-08-08</date>
// <summary>Entities used for connect WebParts and Lists content.</summary> using System;
using System.Collections.Generic;
using Deloitte.Gdc.KM.Utils; namespace Deloitte.Gdc.KM.WebParts.Entities
{
/// <summary>
/// Class ServiceOfferingContent.
/// </summary>
public class ServiceOfferingContent : IComparable<ServiceOfferingContent>
{ /// <summary>
/// Gets or sets the index.
/// </summary>
/// <value>The index.</value>
public string Index { get; set; } /// <summary>
/// Compares to.
/// </summary>
/// <param name="other">The other.</param>
/// <returns>System.Int32.</returns>
public int CompareTo(ServiceOfferingContent other)
{
if (other == null) return -;
if (Index.ToInt() > other.Index.ToInt())
{
return -;
}
return ;
}
}
}