如何对EntitySet <T>进行排序

Chr*_*nes 1 .net sorting data-binding entityset linq-to-sql

MSDN文档声明EntitySet实现IBindingList

(请参阅http://msdn.microsoft.com/en-us/library/bb546190.aspx上的 "绑定到EntitySets" )

但是,可以清楚地看到EntitySet没有实现此接口!

那我怎么排序?

对于上下文,我将此集绑定到WPF ListView.

对于我试图解决的问题的更广泛的背景,请看这篇文章.

jri*_*sta 7

EntitySet <T>没有实现IBindingList ...它提供了一个获取IBindingList的方法.您需要调用.GetNewBindingList()来获取EntitySetBindingList <T>的实例,该实例派生自SortableBindingList <T>,它是BindingList <T>.EntitySetBindingList只是它创建的原始EntitySet <T>的包装器,因此对它的任何修改都是对原始EntitySet的修改.

编辑:使用BindingList排序:

要使用BindingList进行排序,您需要公开某种类型的接口以允许排序.BindingList <T>类支持排序,但它通过受保护的属性和方法.应该可以使用包装器公开表达式排序方法:

public class EntitySetBindingWrapper<T>: BindingList<T>
{
    public EntitySetBindingWrapper(BindingList<T> root) : base(root)
    {
    }

    public void Sort(Expression<Func<T, P>> expr, ListSortDirection direction)
    {
        if (expr == null)
            base.RemoveSortCore();

        MemberExpression propExpr = expr as MemberExpression;
        if (propExpr == null) throw new ArgumentException("You must provide a property", "expr");

        PropertyDescriptorCollection descriptorCol = TypeDescriptor.GetProperties(typeof(T));
        IEnumerable<PropertyDescriptor> descriptors = descriptorCol.Cast<PropertyDescriptor>();
        PropertyDescriptor descriptor = descriptors.First(pd => pd.Name == propExpr.Member.Name);

        base.ApplySortCore(descriptor, direction);
    }
}
Run Code Online (Sandbox Code Playgroud)

那么您应该能够这样排序:

var bindingWrapper = new EntitySetBindingWrapper(myEntitySet.GetNewBindingList());
bindingWrapper.Sort(e => e.MyProperty, ListSortDirection.Ascending);

listView.DataSource = bindingWrapper;
Run Code Online (Sandbox Code Playgroud)

EntitySetBindingWrapper类可能还有其他实现...例如将BindingList <T>上的任何常用公共方法转发给提供给构造函数的方法.