【问题标题】:How to sort list of Control type如何对控件类型列表进行排序
【发布时间】:2021-12-12 23:54:09
【问题描述】:

我在这样的表单上创建了控件列表:

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

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

list.Sort();

但它告诉我System.InvalidOperationException: 'Failed to compare two elements in the array.' ArgumentException: At least one object must implement IComparable.

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

【问题讨论】:

  • var labels = this.Controls.OfType&lt;Label&gt;().OrderBy(L =&gt; L.TabIndex);

标签: c# list winforms sorting controls


【解决方案1】:

您可以使用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;}
}

【讨论】:

    【解决方案2】:

    您可以将Comparison 函数传递给list.Sort

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

    【讨论】:

      猜你喜欢
      • 2020-02-23
      • 2011-02-10
      • 1970-01-01
      • 2016-04-17
      • 2016-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多