WideWood
WideWood

Reputation: 569

How to sort list of Control type

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?

Upvotes: 2

Views: 748

Answers (2)

Charlieface
Charlieface

Reputation: 71952

You can pass a Comparison function to list.Sort

var list = this.Controls.OfType<Label>().ToList();
list.Sort((a, b) => a.TabIndex.CompareTo(b.TabIndex));

Upvotes: 1

KGEM
KGEM

Reputation: 99

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

Upvotes: 3

Related Questions