C# List<>排序的实例介绍

发布时间:2020-02-18编辑:脚本学堂
为大家介绍c#中对List<>进行排序的代码,主要是通过例子帮助大家了解List<>排序,有需要的朋友,可以参考下。

说明:List<>类型可以支持对任意类型的存储,也可以对其进行排序。

以下为大家介绍一种简单的排序实现方法。

1、定义一个类CAttributeFeature,后面用List<CAttributeFeature>存储该类的列表。

public class CAttributeFeature
{
 public string m_strAttributeName { get; set; }
 public double m_dAttributeFeature { get; set; }
 public CAttributeFeature(string strName, double dFeature)
 {
     this.m_strAttributeName = strName;
     this.m_dAttributeFeature = dFeature;
 }

 public void FeatureAdd(double dFeature)
 {
   this.m_dAttributeFeature += dFeature;
 }
}

2、定义一个函数SortCompare(),对List<CAttributeFeature>进行排序时作为参数使用:

#region SortCompare()函数,对List<CAttributeFeature>进行排序时作为参数使用
/// <summary>
/// 对List<CAttributeFeature>进行排序时作为参数使用
/// </summary>
/// <param name="AF1"></param>
/// <param name="AF2"></param>
/// <returns></returns>
///by http://www.jb200.com
private static int SortCompare(CAttributeFeature AF1, CAttributeFeature AF2)
{
int res = 0;
if (AF1.m_dAttributeFeature > AF2.m_dAttributeFeature)
{
 res = -1;
}
else if (AF1.m_dAttributeFeature < AF2.m_dAttributeFeature)
{
 res = 1;
}
return res;
}
#endregion

3、产生一个List<CAttributeFeature>的对象,将前一步定义的SortCompare()函数做为Sort()方法的参数传入,对List<CAttributeFeature>进行排序。

List<CAttributeFeature> listAF = m_nDTreeGenerator1.Chaos_GetUsefulAttributeFeature(Chaos_DTree1);
//按其特征值进行排序
listAF.Sort(SortCompare);