Search code examples
c#linqlambda

Get a collection of single objects among groups in LINQ or Lambda Expression


I have a collection of categories, each of the categories contains a collection of models.

I want to get a collection of models from these instances.

var topModels = Model.Categories.Select(c => c.TopModels ?? Enumerable.Empty<MyModel>());

If I wrote like the above, it returns a collection of collections (IEnumerable<IEnumerable<MyModel>>). But I need something like IEnumerable<MyModel>.

I just don't know how to get them right in a simple way.


Solution

  • Using Select on IEnumerable<T> will return IEnumerable<T>. This is applied to your case too.

    Since c (that is, the T) contains IEnumerable<MyModel> (which is in a variable called TopModels), your Select return IEnumerable<T> which is IEnumerable<IEnumerable<MyModel>>

    Look at the SelectMany instead. It is used to "flatten" your IEnumerable<IEnumerable<T>> to IEnumerable<T>. That is, using SelectMany on IEnumerable<IEnumerable<T>> will return IEnumerable<T>

    Something like:

    var topModelsEnumerable = Model.Categories.SelectMany(c => c.TopModels != null);
    

    Check this.