BindingList和LINQ?

时间:2008-11-25 19:52:53

标签: c# .net linq .net-3.5 c#-3.0

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

 var orderedList = //Here is linq query
 return (BindingList<MyObject>)orderedList;

这已编译但未能执行,有什么诀窍?

3 个答案:

答案 0 :(得分:18)

new BindingList<MyObject>(orderedList.ToList())

答案 1 :(得分:3)

您无法始终将任何集合类型转换为任何其他集合。关于编译器何时检查强制转换,请查看Compile-time vs runtime casting

上的这篇文章

但是,您可以通过自己做一些管道从容器中轻松生成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()

答案 2 :(得分:2)

上述内容仅在您的linq查询的选择投影显式键入MyObject而不是select new创建匿名对象实例时才有效。在这种情况下,typeof(orderedList.ToList())最终会变成类似于:System.Collections.Generic.List&lt;&lt;&gt; f__AnonymousType1&gt;

即:这应该有效:

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&lt;&lt;&gt; f__AnonymousType2&gt; (类型参数匹配选择投影中设置的属性)

参考:http://blogs.msdn.com/swiss_dpe_team/archive/2008/01/25/using-your-own-defined-type-in-a-linq-query-expression.aspx

相关问题