girlcode
girlcode

Reputation: 3265

LINQ to Objects converting to list to display in gridview

I am trying to use LINQ to Objects to bind a list of books to a gridview. Author and Book are custom objects, where "Books" is defined in the Author class as a list.

    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();

However I get the following error:

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__aa1.MoveNext() at System.Collections.Generic.List1..ctor(IEnumerable1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)

What am I doing wrong here?

Upvotes: 0

Views: 1576

Answers (2)

Jens Kloster
Jens Kloster

Reputation: 11287

I Think the problem is that books is a collection. So you actually get a collection of collections of books

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

Using a SelectMany will turn your collection of books collection into one of books :-)

You could also replease your Cast with the SelectMany:

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

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

Upvotes: 1

Prince
Prince

Reputation: 338

This is just an Idea, otherwise I think you have fine. var books = (from s in authors where s.LastName == "Jones" select s.Books).Tolist(); and pass this directly GridView2.DataSource = books ; GridView2.DataBind();

This might work..

Upvotes: 0

Related Questions