Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Sub objects based on value using linq?

Tags:

c#

.net

lambda

linq

Top Tier Object
        SubTier Objects
            SubSubTier Objects 1.1,1.2,1.3 : SubTierId = 2
            SubSubTier Objects 2.1,2.2,1.3 : SubTierId = 3
        SubTier Objects
            SubSubTier Objects 3.1,3.2,3.3 : SubTierId = 1
            SubSubTier Objects 4.1,4.2,4.3 : SubTierId = 2

Expected end results is to get an IEnumerable with 1.2, 2.3, 3.1, 4.2 which represents the SubTierId of each subTier.

SubSubTiers mySubSubTier = allTiers.Select(topTier => 
            topTier.SubTiers.Where(sbTier => sbTier.Id == topTier.SubTierId));

but what happens is I get this return type.

IEnumerable<IEnumerable<SubSubTier>>

What is the best way so that I just get a single IEnumerable of the SubSubTier?

like image 997
MichaelChan Avatar asked Sep 27 '22 20:09

MichaelChan


1 Answers

You can use SelectMany instead of Select

SubSubTiers mySubSubTier = allTiers.SelectMany(topTier => 
        topTier.SubTiers.Where(sbTier => sbTier.Id == topTier.SubTierId));

it will select subtiers into combined IEnumerable instead of IEnumerable of IEnumerables

like image 80
Kamil Budziewski Avatar answered Oct 04 '22 13:10

Kamil Budziewski