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

Dung Do Tien Dec 15 2020 472

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.
  • S

    Sandeep Kumar Dec 15 2020

    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.

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

X Close