MeepMania MeepMania - 1 year ago 75
C# Question

How to sort numbers in a table?

I've got a rather small table containing two columns - one is string and one is supposed to be numbers (I know, everything in a table is just "object").
Is there any way to convert the objects into for example Int or Double to be able to actually sort it in a reasonable way?

enter image description here

The sources for that table are two lists. I could sort the number list, but the data wouldn't match anymore.
Other idea would be to transfer the content of the lists into a multidimensional array and to sort that one but I'd prefer a solution to sort that table directly.

Anyone got an idea?

Answer Source

Rather than working with two lists, merge them:

public class MyRow { // rename me
    public int Element { get; set; }
    public int Appearances { get; set; }
var rows = new List<MyRow>();
for(...) {// loop over the two lists...
    rows.Add(new MyRow {
        Element =..., Appearances = ... });
rows.Sort((x,y) => y.Appearances.CompareTo(x.Appearances));

Then either just loop and create cells, or (easier) just set rows as the data-source for the table and let it bind itself.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download