我是Linq的新手,我想对BindingList中的一些数据进行排序。完成Linq查询后,我需要使用BindingList集合来绑定数据。
var orderedList = //Here is linq query
return (BindingList<MyObject>)orderedList;这段代码编译后执行失败,有什么诀窍吗?
发布于 2008-11-25 19:54:41
new BindingList<MyObject>(orderedList.ToList())发布于 2014-03-01 04:23:32
您不能总是将任何集合类型强制转换为任何其他集合。关于编译器何时检查类型转换,请查看Compile-time vs runtime casting上的这篇文章
但是,通过自己做一些工作,您可以很容易地从enumerable生成一个BindingList。只需将以下扩展方法添加到任何可枚举类型上,即可将集合转换为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()发布于 2009-02-11 21:43:59
只有当您的linq查询的选择投影被显式地类型化为MyObject而不是创建匿名对象的实例的select new时,上述方法才有效。在这种情况下,typeof(orderedList.ToList())的结果类似于下面这样: System.Collections.Generic.List<<>f__AnonymousType1>
ie:这应该是可行的:
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> (类型参数与选择投影中设置的属性相匹配)
参考:http://blogs.msdn.com/swiss_dpe_team/archive/2008/01/25/using-your-own-defined-type-in-a-linq-query-expression.aspx
https://stackoverflow.com/questions/318644
复制相似问题