簡體   English   中英

如何填充使用未排序數組排序的列表框

[英]How to populate a listbox sorted with unsorted array

我有一系列具有兩個屬性(名稱和位置)的項目。 該數組沒有以任何方式排序,我想按位置順序填充一個列表框。

我可以使用下面的代碼來做到這一點,首先添加所有項目,這樣我便獲得了一個列表,其中列出了正確數量的項目,然后在正確位置替換了這些項目。 但是我想知道是否有更好的方法呢?

我希望列表框具有以下名稱:Mark,John和James。

注意:James,Mark和John數據只是一個例子,我無法對常規數組進行排序。

public class _standing
{
   public _standing(string _name, int _pos) {
      name = _name;
      position = _pos;
   }
   public string name { get; set; }
   public int position { get; set; }
}

_standing a = new _standing("James", 2);
_standing b = new _standing("Mark", 0);
_standing c = new _standing("John", 1);
_standing[] standing = new _standing[]{a, b, c};

for (int i = 0; i < standing.Length; i++) {
   listBox1.Items.Add(standing[i].name);
}
for (int i = 0; i < standing.Length; i++) {
   listBox1.Items.RemoveAt(standing[i].position);
   listBox1.Items.Insert(standing[i].position, standing[i].name);
}

您可以只使用數組的OrderBy方法:

standing = standing.OrderBy(i => i.position).ToArray();
listBox1.Items.AddRange(standing);

您也可以按降序排列:

standing.OrderByDescending(i => i.position).ToArray();

這些都需要引用System.Linq

另外,由於OrderBy返回了新對象,因此您也可以執行此操作而無需重新排序原始列表:

_standing a = new _standing("James", 2);
_standing b = new _standing("Mark", 0);
_standing c = new _standing("John", 1);
_standing[] standing = new _standing[] { a, b, c };

listBox1.Items.AddRange(standing.OrderBy(i => i.position).ToArray());

更新

為了在listBox1中顯示有意義的內容,您應該在_standing類上重寫ToString方法,例如:

public class _standing
{
    public string name { get; set; }
    public int position { get; set; }

    public _standing(string _name, int _pos)
    {
        name = _name;
        position = _pos;
    }

    public override string ToString()
    {
        return position + ": " + name;
    }
}

最后,我不得不提到您的大小寫/命名約定不是標准的C#。 該標准的目的是將類和屬性設置為PascalCase,將參數設置為camelCase,將私有字段設置為帶有可選下划線前綴的pascalCase。 因此,理想情況下,您的代碼應類似於:

public class Standing
{
    public string Name { get; set; }
    public int Position { get; set; }

    public Standing(string name, int position)
    {
        Name = name;
        Position = position;
    }

    public override string ToString()
    {
        return Position + ": " + Name;
    }
}

和...

Standing a = new Standing("James", 2);
Standing b = new Standing("Mark", 0);
Standing c = new Standing("John", 1);
Standing[] standing = { a, b, c };

listBox1.Items.AddRange(standing.OrderBy(i => i.Position).ToArray());

如果您是我,我會先創建一個_standing列表並添加到列表中。 就像是:

List<_standing> standingList = new List<_standing>();
standingList.Add(new _standing("James", 2)); 
etc...

使用List而不是數組類型的優點是它的大小是動態的。 如果您只打算擁有3個_standing對象,那么數組就可以了,但實際上可能不太可能。

然后,您可以使用Linq查詢按位置對列表進行排序

IEnumerable<_standing> sorted = standingList.OrderBy(stand => stand.Position);

現在,您已經擁有使用.NET內置排序算法的排序列表,可以將其添加到控件Items集合中。 您可以使用AddRange方法節省時間:

listBox1.Items.AddRange(sorted);

供參考的來源:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM