lefou February 2016

Creating lists from another list's item in Linq

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

Answers


Zippy February 2016

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
            };


Rahul Singh February 2016

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 
                                                              });


fubo February 2016

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 }));

Post Status

Asked in February 2016
Viewed 2,567 times
Voted 6
Answered 3 times

Search




Leave an answer