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; } } }
