Lovethenakedgun
Lovethenakedgun

Reputation: 845

LINQ Query: Aggregate child sets from a set of objects

If I have an ArtGallery object that contains a set of Exhibits, which each contain a set of Artworks, how would I structure a LINQ query to return a set containing all Artworks in the ArtGallery.

I can do it without LINQ via something like:

Set<Artwork> artworkSet = null;
    foreach (var exhib in ArtGallery.Exhibits)
        foreach (var art in exhib.Artworks)
            artworkSet.Add(art);

Just wondering if there was something a bit more elegant

Upvotes: 0

Views: 50

Answers (2)

Dmitry Korolev
Dmitry Korolev

Reputation: 675

SelectMany will project each exhibit to a collection of art works and then will flatten all the collection into one:

var artworkSet = ArtGallery.Exhibits.SelectMany(x => x.Artworks);

Upvotes: 1

Maharajan
Maharajan

Reputation: 51

You can use linq to get it.

artworks.Exhibits.SelectMany(x => x.ArtWorks).ToList();

Upvotes: 1

Related Questions