BindingList和LINQ?

Pat*_*ins 13 .net c# linq .net-3.5 c#-3.0

我是Linq的新手,我想对BindingList中的一些数据进行排序.一旦我完成了Linq查询,我需要使用BindingList集合来绑定我的数据.

 var orderedList = //Here is linq query
 return (BindingList<MyObject>)orderedList;
Run Code Online (Sandbox Code Playgroud)

这个编译但执行失败,有什么诀窍?

lep*_*pie 18

new BindingList<MyObject>(orderedList.ToList())
Run Code Online (Sandbox Code Playgroud)

  • 这不会打破任何订阅列表上的活动的人吗? (3认同)

Kyl*_*Mit 5

您不能总是将任何集合类型转换为任何其他集合。关于编译器何时检查强制转换,请查看关于编译时与运行时强制转换的这篇文章

但是,您可以BindingList通过自己进行一些管道操作,轻松地从可枚举中生成 a 。只需将以下扩展方法添加到任何 Enumerable 类型即可将集合转换为 BindingList。

C#

static class ExtensionMethods
{
    public static BindingList<T> ToBindingList<T>(this IEnumerable<T> range)
    {
        return new BindingList<T>(range.ToList());
    }
}

//use like this:
var newBindingList = (from i in new[]{1,2,3,4} select i).ToBindingList();
Run Code Online (Sandbox Code Playgroud)

VB

Module ExtensionMethods
    <Extension()> _
    Public Function ToBindingList(Of T)(ByVal range As IEnumerable(Of T)) As BindingList(Of T)
        Return New BindingList(Of T)(range.ToList())
    End Function
End Module

'use like this:
Dim newBindingList = (From i In {1, 2, 3, 4}).ToBindingList()
Run Code Online (Sandbox Code Playgroud)