如何排序BindingList <t>?

时间:2016-09-26 21:01:36

标签: c# winforms

我在BindingList<MyClass>中存储了数千个MyClass对象。我想按日期属性MyClass.dt对它们进行排序。

Class BindingList不支持直接排序。我如何排序BindingList<T>不制作所有对象的重复副本?我需要按升序排序,请按降序排序。

我不需要BindingList.Sort() to behave like a List.Sort()中描述的特殊课程SortableBindingList。我在一两行代码中寻找简短的解决方案。

3 个答案:

答案 0 :(得分:4)

Linq会工作的。

var sortedListInstance = new BindingList<MyClass>(unsortedListInstance.OrderBy(x => x.dt).ToList());

请记住,您会获得排序列表的浅层副本,而不是MyClass的重复实例。

不要忘记将命名空间包含在代码文件的顶部System.Linq

答案 1 :(得分:4)

在BindingList上实现Sort的快速方法是使用constructor that takes a backing IList< T >作为参数。您可以使用List<T>作为支持,并获得其Sort功能。

根据documentation

  

使用此BindingList创建一个由list支持的BindingList,这可确保对列表的更改反映在BindingList中。

如果您的MyClass定义为:

internal class MyClass
{
    public MyClass(string name, Int32 num)
    {
        this.Name = name;
        this.Num = num;
    }
    public string Name {get; set;}
    public Int32 Num {get; set;}
}

然后你可以做这样的事情来对Num字段进行排序。

private List<MyClass> backing;
private BindingList<MyClass> bl;

    private void InitializeBindingList()
        {
            backing = new List<MyClass>();
            bl = new BindingList<MyClass>(backing);
            bl.Add(new MyClass("a", 32));
            bl.Add(new MyClass("b", 23));
            bl.Add(new MyClass("c", 11));
            bl.Add(new MyClass("d", 34));
            bl.Add(new MyClass("e", 53));
        }

    private void SortBindingList()
        {
            backing.Sort((MyClass X, MyClass Y) => X.Num.CompareTo(Y.Num));
            // tell the bindinglist to raise a list change event so that 
            // bound controls reflect the new item order
            bl.ResetBindings();
        }
    }

您需要在对备份列表进行排序后调用BindingList.ResetBindings方法,以通知任何绑定控件BindingList已更改并更新控件。

答案 2 :(得分:-1)

//Convert it to a data table, then the Automatic will work.
DataGridView.DataSource = ConvertToDataTable(MyList).DefaultView;

public DataTable ConvertToDataTable(IBindingList list)
{
   DataTable dt = new DataTable();

   if (list.Count > 0)
   {
      Type typ = list[0].GetType();

      PropertyInfo[] arrProps = typ.GetProperties();

      foreach (PropertyInfo pi in arrProps)
      {

         Type colType = pi.PropertyType;
         if (colType.IsGenericType)
         {
            colType = colType.GetGenericArguments()[0];
         }

         dt.Columns.Add(pi.Name, colType);
      }

      foreach (object obj in list)
      {
         DataRow dr = dt.NewRow();

         foreach (PropertyInfo pi in arrProps)
         {
            if (pi.GetValue(obj, null) == null)
               dr[pi.Name] = DBNull.Value;
            else
               dr[pi.Name] = pi.GetValue(obj, null);
         }

         dt.Rows.Add(dr);
      }
   }
   return dt;
}
相关问题