我是新的Linq,我想对BindingList中的一些数据进行排序。一旦我做了我的Linq查询,我需要使用BindingList集合来绑定我的数据。BindingList和LINQ?
var orderedList = //Here is linq query
return (BindingList<MyObject>)orderedList;
这编译但失败执行,有什么窍门?
我是新的Linq,我想对BindingList中的一些数据进行排序。一旦我做了我的Linq查询,我需要使用BindingList集合来绑定我的数据。BindingList和LINQ?
var orderedList = //Here is linq query
return (BindingList<MyObject>)orderedList;
这编译但失败执行,有什么窍门?
new BindingList<MyObject>(orderedList.ToList())
,上面当你的LINQ查询的选择投影显式类型为MyObject的,而不是选择新的它创建一个匿名对象的实例才有效。在这种情况下将typeof(orderedList.ToList())卷起,以这种类似的东西:System.Collections.Generic.List < <> f__AnonymousType1>
即:这应该工作:
var result = (from x in MyObjects
where (wherePredicate(x))
select new MyObject {
Prop1 = x.Prop1,
Prop2 = x.Prop2
}).ToList();
return new BindingList<MyObject>(result);
这不会:
var result = from x in db.MyObjects
where(Predicate(x))
select new {
Prop1 = x.Prop1
Prop2 = x.Prop2
};
return new BindingList<MyObject>(result.ToList())
//creates the error: CS0030 "Cannot convert type 'AnonymousType#1' to 'MyObject'
在他们的typeof(结果)第二种情况是:System.Collections.Generic.List < <> f__AnonymousType2>(类型PARAMS匹配您选择投影设置属性)
你不能总是施放任何集合类型到任何其他集合。在编译器检查铸件的时候,看看这个贴子Compile-time vs runtime casting
但是,你可以通过自己做一些管道来轻松地从enumerable生成BindingList
。只需将以下扩展方法添加到任何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();
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()
这会不会打破谁的订阅列表上的事件谁? – GWLlosa 2009-07-16 19:14:11