2013-05-02 50 views
0

我正在尝试使用LINQ to Objects将书籍列表绑定到gridview。作者和书籍是自定义对象,其中“作品”在作者类中定义为列表。LINQ to Objects转换为列表以显示在gridview中

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: Server was unable to process request. --->

System.InvalidCastException: Unable to cast object of type

'System.Collections.Generic.List`1[Book]' to type 'Book'.

at System.Linq.Enumerable.d__aa 1.MoveNext() at System.Collections.Generic.List 1..ctor(IEnumerable 1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable 1 source)

我在做什么错在这里?

+0

可能您有2种不同的书籍类型。一个来自webservice,另一个来自你的项目。 – Andrei 2013-05-02 09:40:13

回答

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 会变成你的藏书收集到的一本书:-)

你也可以replease你Cast用的SelectMany:

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

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

工作完美,谢谢:) – socketman 2013-05-02 17:33:55

0

这只是一个想法,否则我认为你很好。 var books =(from s in authors where s.LastName ==“Jones” select s.Books).Tolist(); 并直接传递 GridView2.DataSource = books; GridView2.DataBind();

这可能工作..

+0

这给了我以下错误:不能隐式转换类型'System.Collections.Generic.List >'到'System.Collections.Generic.List ' – socketman 2013-05-02 05:00:07

+0

做一件事。请粘贴“//作者/书籍列表在此填充”的代码。粘贴这个集合和作者类的绑定代码,它的定义。我认为只是类型不匹配 – Prince 2013-05-02 05:03:23