【问题标题】:LINQ to Objects converting to list to display in gridviewLINQ to Objects 转换为列表以在 gridview 中显示
【发布时间】:2013-05-02 04:46:09
【问题描述】:

我正在尝试使用 LINQ to Objects 将书籍列表绑定到网格视图。 Author 和 Book 是自定义对象,其中“Books”在 Author 类中定义为列表。

    List<Author> authors = new List<Author>();
    // list of authors/books is populated here
    var books = from s in authors
                       where s.LastName == "Jones"
                       select s.Books;

    GridView2.DataSource = books.AsEnumerable().Cast<Book>().ToList();
    GridView2.DataBind();

但是我收到以下错误:

System.Web.Services.Protocols.SoapException:服务器无法 处理请求。 --->

System.InvalidCastException:无法转换类型的对象

'System.Collections.Generic.List`1[Book]' 输入'Book'。

在 System.Linq.Enumerable.d__aa1.MoveNext() at System.Collections.Generic.List1..ctor(IEnumerable1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable1 源)

我在这里做错了什么?

【问题讨论】:

  • 您可能有 2 种不同的图书类型。一个来自 web 服务,另一个在您的项目中。

标签: c# asp.net linq web-applications linq-to-objects


【解决方案1】:

我认为问题在于书籍是一个集合。 所以你实际上得到了一系列书籍的集合

// list of authors/books is populated here
var books = (from s in authors
                   where s.LastName == "Jones"
                   select s.Books).SelectMany(c=>c);

使用SelectMany 会将您收藏的书籍收藏变成其中一本书 :-)

您也可以使用 SelectMany 回复您的Cast:

 var books = from s in authors
                       where s.LastName == "Jones"
                       select s.Books;

    GridView2.DataSource = books.SelectMany(c => c).ToList();
    GridView2.DataBind();

【讨论】:

    【解决方案2】:

    这只是一个想法,否则我认为你很好。 var books =(来自 authors 中的 s 其中 s.LastName == "琼斯" 选择 s.Books).Tolist(); 并直接通过 GridView2.DataSource = 书籍; GridView2.DataBind();

    这可能行得通..

    【讨论】:

    • 这给了我以下错误:无法将类型'System.Collections.Generic.List>'隐式转换为'System.Collections.Generic.List'
    • 做一件事。请粘贴“//此处填充作者/书籍列表”的代码。粘贴绑定此集合的代码以及作者类及其定义。我认为只是类型不匹配
    猜你喜欢
    • 1970-01-01
    • 2011-10-24
    • 2017-12-25
    • 1970-01-01
    • 2011-06-04
    • 1970-01-01
    • 2013-05-30
    • 2018-03-03
    • 1970-01-01
    相关资源
    最近更新 更多