【问题标题】:How to sort a list of Classes如何对类列表进行排序
【发布时间】:2018-08-31 08:43:00
【问题描述】:

我有一个名为 DataStore 的类,其中我有以下内容;

string Name;
DateTime Date;
double Code;

在主表单中,我有以下列表;

List<DataStore> ListOfDataStore = new List<DataStore>

我在主窗体中创建此类的实例,并根据用户输入的内容分配值并将它们存储在下面的列表中;

 DataStore dataStore = new DataStore();
 dataStore.Name = "abc";
 dataStore.Date = new DateTime(Year,Month,Day);
 dataStore.Code = 10;
 ListOfDataStore.Add(dataStore);

 DataStore dataStore = new DataStore();
 dataStore.Name = "def";
 dataStore.Date = new DateTime(Year,Month,Day);
 dataStore.Code = 20;
 ListOfDataStore.Add(dataStore);

 DataStore dataStore = new DataStore();
 dataStore.Name = "ghi";
 dataStore.Date = new DateTime(Year,Month,Day);
 dataStore.Code = 30;
 ListOfDataStore.Add(dataStore);

我现在想按每个 dataStore.Name 中的内容对 ListOfDataStore 进行排序,但如果不提供 ListOfDataStore 列表的索引,我无法弄清楚如何访问字符串 Name。

非常感谢任何指导。

【问题讨论】:

    标签: c# winforms list linq sorting


    【解决方案1】:

    如果你想对列表进行适当的排序:

    ListOfDataStore.Sort((x, y) => x.Name.CompareTo(y.Name));
    

    如果你想要一个按名称排序的新集合:

    var orderedListOfDataStore = ListOfDataStore.OrderBy(item => item.Name);
    

    【讨论】:

      【解决方案2】:

      LinQ 可以通过OrderByOrderByDescending 方法帮助您订购列表

      var sorted = ListOfDataStore.OrderBy(d=> d.Name)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-02-23
        • 1970-01-01
        • 2012-12-16
        • 2011-02-10
        • 2021-12-12
        • 1970-01-01
        相关资源
        最近更新 更多