我在表單上創建了這樣的控制元件串列:
List<Control> list = new List<Control>();
foreach (Control c in this.Controls)
{
if (c.GetType() == typeof(Label))
{
list.Add(c);
}
}
這個串列中的所有控制元件都是標簽,所以我需要按升序對這個控制元件串列進行排序,所以我使用了 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方法或者我應該使用什么來代替這個方法?
uj5u.com熱心網友回復:
您可以使用OrderBy的IEnumerable 介面方法并為其提供一個函式,該函式指定您要比較的元素作為使用排序的替代方法。
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;}
}
uj5u.com熱心網友回復:
您可以將Comparison函式傳遞給list.Sort
var list = this.Controls.OfType<Label>().ToList();
list.Sort((a, b) => a.TabIndex.CompareTo(b.TabIndex));
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/339207.html
