How to convert sublists to a flat list using LINQ in C#

Dung Do Tien Dec 15 2020 63

In C#, I have a list as below :

public class Brand{
   public string Name {get; set;}
   public List<string> Models {get; set}
}

Now I want to get all value from Models properties and push it into a list variable.

I tried using LinQ with Select() method as below but it does not work for me.

List<Brand> lstBrands = _brandBo.GetList();
List<string> lstModel = lstBrands.Select(x => x.Model.Select(y => y).ToList()).ToList();

lstModel always return a nested list. Thanks for any solution.

Have 1 answer(s) found.
  • You can use SelectMany() of LinQ to merge many sublists into a list. You can do as below:

    List<Brand> lstBrands = _brandBo.GetList();
    List<string> lstModel = lstBrands.SelectMany(x => x.Model.Select(y => y)).ToList();  

    I hope it is helpful for you.

    Sandeep Kumar Dec 15 2020
Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips