Linq: Query Nested Collections

Just a quicknote – if you have a collection of objects (of a given type) where each object of that type contains its own collection, you can select all items across the nested collections by using multiple from statements.

As an example, imagine a case where you have a collection of objects that each has a collection of KeyValues pairs. The code below allows you to select all distinct keys from those key values pairs.

var distinctKeys = (from i in Items
                    from nested in i.SecondLevelCollection
                    orderby nested.SomeProperty ascending
                    select nested.SomeProperty).Distinct();

Unrelated quicknote: Use the Intersect extension method to find object common to two collections (obvious really!)  e.g.

var common = ColectionA.Intersect(CollectionB);

You May Also Like

About the Author: rnowik

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.