C#利用iComparable接口實現List排序


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 -1;
            if (Index.ToInt() > other.Index.ToInt())
            {
                return -1;
            }
            return 1;
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM