c# - 如何对控件类型列表进行排序

标签 c# list winforms sorting controls

我在表单上创建了如下控件列表:

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

此列表中的所有控件都是标签,因此我需要对 Controls 的此列表进行排序按升序排列,所以我使用 Sort List类的方法如下:

list.Sort();

但它对我说System.InvalidOperationException:“无法比较数组中的两个元素。” ArgumentException:至少一个对象必须实现 IComparable。

因为我想使用TabIndex对其进行排序值或至少其 Name ,我不清楚。我应该传递什么给Sort方法或者我应该使用什么来代替这个方法?

最佳答案

您可以使用IEnumerable interface method of OrderBy并为其提供一个函数,指定要比较的元素作为使用排序的替代方法。

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

关于c# - 如何对控件类型列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69742910/

相关文章:

list - 如何在包含重复项的排序列表的非连续 float 元素之间填充零?

c# - 将帮助图标添加到 WinForms 表单标题栏

vb.net - Option Strict On,设置未知对象类型的焦点

c# - 只读属性的最佳方法是什么

c# - 如果从代码触发异常以在 C# 中重新定义运算符,会发生什么情况?

c++ - 如何将 'const Obj' 插入 std::list<T*>?

r - 将列表粘贴到矢量,为每个矢量级别重复列表

c# - 为什么此实体的属性缺少 SET 语句

c# - 在 MS Word 中加载 Word Addin

.net - Control.EndInvoke 为异常重置调用堆栈