Home > OS >  How to sort list of Control type
How to sort list of Control type

Time:10-28

I created list of controls on form like this:

            List<Control> list = new List<Control>();
            foreach (Control c in this.Controls)
            {
                if (c.GetType() == typeof(Label))
                {
                    list.Add(c);
                }
            }

All controls in this list are Labels so I need to sort this list of Controls in ascending order, so I use Sort method of List class like this:

list.Sort();

But it says to me System.InvalidOperationException: 'Failed to compare two elements in the array.' ArgumentException: At least one object must implement IComparable.

Since I want to sort it using TabIndex value or at least its Name, it's unclear for me. What should I pass to Sort method or what should I use instead of this method?

CodePudding user response:

You can use the IEnumerable interface method of OrderBy and provide it with a function that specifies what element you are comparing as an alternative to using sort.

using System;
using System.Collections.Generic;
using System.Linq;
                    
public class Program
{
    public static void Main()
    {
        var controls = new List<B>() {new B() {Index = 0}, new B() {Index = -1}};
        var sortedControls = controls.OrderBy(x => x.Index).ToList();
        Console.WriteLine(controls[0].Index); // -1
        Console.WriteLine(controls[1].Index); // 0
    }
}

public class B
{
    public int Index {get; set;}
}
  • Related