Sorting a list in C# with Icomparer

342 Views Asked by At

I want to sort the items in a combobox on the object.Frequency. I did some research and then I made this class:

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

Then, to put my objects in the combobox (unsorted) I use:

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

But obviously I want that combobox to be sorted to Frequency. Where it is now:

  1. Accipiter(2)
  2. Allauda (1)
  3. Anas (6) ...

it Should be

  1. Anas(6)
  2. Accipiter(2)
  3. Allauda(1)

Thank you in advance

1

There are 1 best solutions below

0
On

Well, wouldn't it be easier to do

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