在C#中对List<>进行排序
我们知道List<>类型可以支持对任意类型的存储,我们也可以对其进行排序。现介绍一种较为简单的方法:
1、我们先定义一个类CAttributeFeature,后面我们用List<CAttributeFeature>来存储该类的一个列表,代码如下:
1: public class CAttributeFeature
2: {
3: public string m_strAttributeName { get; set; }
4: public double m_dAttributeFeature { get; set; }
5:
6: public CAttributeFeature(string strName, double dFeature)
7: {
8: this.m_strAttributeName = strName;
9: this.m_dAttributeFeature = dFeature;
10: }
11:
12: public void FeatureAdd(double dFeature)
13: {
14: this.m_dAttributeFeature += dFeature;
15: }
16: }
2、我们定义一个函数SortCompare(),对List<CAttributeFeature>进行排序时作为参数使用,代码如下:
1: #region SortCompare()函数,对List<CAttributeFeature>进行排序时作为参数使用
2: /// <summary>
3: /// 对List<CAttributeFeature>进行排序时作为参数使用
4: /// </summary>
5: /// <param name="AF1"></param>
6: /// <param name="AF2"></param>
7: /// <returns></returns>
8: private static int SortCompare(CAttributeFeature AF1, CAttributeFeature AF2)
9: {
10: int res = 0;
11: if (AF1.m_dAttributeFeature > AF2.m_dAttributeFeature)
12: {
13: res = -1;
14: }
15: else if (AF1.m_dAttributeFeature < AF2.m_dAttributeFeature)
16: {
17: res = 1;
18: }
19: return res;
20: }
21: #endregion
3、产生一个List<CAttributeFeature>的对象,将前一步定义的SortCompare()函数做为Sort()方法的参数传入,就可以对List<CAttributeFeature>进行排序了。代码如下:
1: List<CAttributeFeature> listAF = m_nDTreeGenerator1.Chaos_GetUsefulAttributeFeature(Chaos_DTree1);
2:
3: //按其特征值进行排序
4: listAF.Sort(SortCompare);