我在表单上创建了如下控件列表:
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/