首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BindingList和LINQ?

BindingList和LINQ?
EN

Stack Overflow用户
提问于 2008-11-25 19:52:53
回答 3查看 18.7K关注 0票数 14

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

代码语言:javascript
复制
 var orderedList = //Here is linq query
 return (BindingList<MyObject>)orderedList;

这段代码编译后执行失败,有什么诀窍吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2008-11-25 19:54:41

代码语言:javascript
复制
new BindingList<MyObject>(orderedList.ToList())
票数 19
EN

Stack Overflow用户

发布于 2014-03-01 04:23:32

您不能总是将任何集合类型强制转换为任何其他集合。关于编译器何时检查类型转换,请查看Compile-time vs runtime casting上的这篇文章

但是,通过自己做一些工作,您可以很容易地从enumerable生成一个BindingList。只需将以下扩展方法添加到任何可枚举类型上,即可将集合转换为BindingList。

C#

代码语言:javascript
复制
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

代码语言:javascript
复制
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()
票数 5
EN

Stack Overflow用户

发布于 2009-02-11 21:43:59

只有当您的linq查询的选择投影被显式地类型化为MyObject而不是创建匿名对象的实例的select new时,上述方法才有效。在这种情况下,typeof(orderedList.ToList())的结果类似于下面这样: System.Collections.Generic.List<<>f__AnonymousType1>

ie:这应该是可行的:

代码语言:javascript
复制
var result = (from x in MyObjects
              where (wherePredicate( x ))
              select new MyObject {
                  Prop1 = x.Prop1,
                  Prop2 = x.Prop2
              }).ToList();
return new BindingList<MyObject>( result );

这不会:

代码语言:javascript
复制
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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/318644

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档