使用Icomparer在C#中对列表进行排序

时间:2013-09-03 09:07:40

标签: c# icomparer

我想在object.Frequency上对组合框中的项进行排序。我做了一些研究,然后我做了这个课:

 public class CompareByFrequency : IComparer<GenderFrequency>
 {
    public int Compare(GenderFrequency x, GenderFrequency y)
    {
        return x.Frequency.CompareTo(y.Frequency);
    }

    public static void QSFreq(List<GenderFrequency> g)
    {
        g.Sort(new CompareByFrequency());
    }
}

然后,为了将我的对象放在组合框中(未分类),我使用:

private void showGenderfreq()
{
    cboGenderFreqs.Items.Clear();
    foreach (GenderFrequency gf in GenderFrequency.GenderFrequencies(
             Bird.getBirdFromCSV(txtFile.Text)))
    {
        cboGenderFreqs.Items.Add(gf);
    }
}

但显然我希望将组合框分类到频率。 它现在在哪里:

  1. 凤头(2)
  2. Allauda(1)
  3. 阿纳斯(6) ...
  4. 应该是

    1. 鸭(6)
    2. 凤头(2)
    3. Allauda(1)
    4. 提前谢谢

1 个答案:

答案 0 :(得分:1)

嗯,这样做不会更容易

cboGenderFreqs.Items.Clear();
cboGenderFreqs.Items.AddRange(
   GenderFrequency.GenderFrequencies.OrderByDescending(gf => gf.Frequency)
   .ToArray());