1

I have a list of a custom car object List<Car>. The car class has two properties 'BrandName' and 'Models' as defined below.

public class Car
{
     public string BrandName {get; set;}
     public List<string> Models {get; set;}
}

The data for the 'List` object is populated from an API as below. It returns close to 200 rows. For illustration purposes, the object has been instantiated with two items as below. The object is returned from the API with this structure and I have no control over how the data is structured and sent.

List<Car> listCarObj = new List<Car>(){
    new Car(){ BrandName = "Mercedes", Models = new List<string>(){"Class A", "Class E"}},
    new Car(){ BrandName = "BMW", Models = new List<string>(){"X Series", "E Series"}}
} 

How do I convert this list to an IEnumerable or another List of an anonymous type having data in the below format using Linq?

var obj = new[] {new {brand = "Mercedes", model = "Class A"},
                 new {brand = "Mercedes", model = "Class E"},
                 new {brand = "BMW", model = "X Series"},
                 new {brand = "BMW", model = "E Series"}};

Thanks in advance..

mantadt
  • 101
  • 1
  • 15

3 Answers3

5

Why don't you make a linq query, in which you select every object from the listCarObj and, for every element from the list, get all the models and return an anonymous type?

Something like:

var obj = from p in listCarObj
          from q in p.Models
          select new {
            brand=p.BrandName,
            model = q
            };
Zippy
  • 1,804
  • 5
  • 27
  • 36
5

here is a approach with SelectMany and a nested Select

var result = listCarObj.SelectMany(x => x.Models.Select(y => new { model = y,brand = x.BrandName }));
fubo
  • 44,811
  • 17
  • 103
  • 137
3

You can use SelectMany to flatten your Models and then project it like this:-

var result = listCarObj.SelectMany(x => x.Models, 
                                       (carObj, model) => new { 
                                                                 carObj.BrandName, model 
                                                              });
Rahul Singh
  • 21,585
  • 6
  • 41
  • 56