如何对项目列表进行排序?

时间:2020-05-04 08:28:04

标签: c# list sorting

C#的新手,这是如此令人困惑,我的代码可能不如某些人所希望的那样整洁。忍受我正在学习。

我有一个名为“ shoppingList”的“商品”列表。

单击“字母”按钮时,我想通过“ Item”类中的“ Name”重新排列“ shoppingList”中的项目。重新排列列表后,该列表将重新绘制在表单上。

我知道这里可能已经有解决方案,但是尝试了许多解决方案后,我只是认为我的知识还不够。如果您仍然知道,请使用宝贝与我说话。也乐意提供更多信息。预先谢谢你

public partial class Form1:Form{
    List<Item> shoppingList = new List<Item>() { };
}

public class Item{
    public Item(string Name, int Amount)
{
        this.name = Name;
        this.amount = Amount;

    }

    public string getname() { return name; }
    public int getamount() { return amount; }

    public int amount;
    public string name;

}

private void alphabetical_Click(object sender, EventArgs e)
{
    //What to put here?
    ProcessAndDrawShoppingList();
}

1 个答案:

答案 0 :(得分:2)

您不仅可以使用.OrderBy()函数吗?

因此,在函数alphabetical_Click中,类似以下内容:

 var sortedList = shoppingList.OrderBy(x => x.Name);  // Guessing that this is the list but I don't know how you have access to it.

或者只需将原始列表设置为已排序列表的值即可

shoppinglist = shoppingList.OrderBy(x => x.Name).ToList();

或者,您可以使用.OrderByDescending()来订购相反的方式。

我不知道这种情况下的列表是什么,但是看起来您正在使用Xamarin / Xamarin.Forms,所以只需从中获取列表并使用OrderBy()函数