Click here to Skip to main content
15,893,622 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello folks.

I have an array of objects (Series) which has a property Books. Books returns an array of Book objects. I would like to construct a List of all the Books in all the Series. I have the following code, which works.
C#
var allBooks = new List<Book>();
foreach (var s in Series)
    allBooks.AddRange(s.Books.ToList());
return allBooks;

However, I was trying to it with a lamda expression:
return Series.Select(s => s.Books.Select(b => b)).ToList();

That didn't work - it told me I was trying to convert an IEnumerable<IEnumerable<Book>> to a List<book>.
As I said, the first bit of code works, but out of curiosity, is there a way to do this with lamda expressions and/or LINQ?
Posted

1 solution

In Linq it is pretty simple:
C#
List<book> GetListFromSeries(Series[] Series)
    {
    var w = from s in Series
            from b in s.Books
            select b;
    return w.ToList<book>();
    }
class Series
    {
    public Book[] Books = new Book[5];
    }
class Book
    {
    public string Title;
    }


[edit]Bloody HTML characters! - OriginalGriff[/edit]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900