Randy Hall Randy Hall - 1 month ago 11
C# Question

Covert IEnumerable to another IEnumerable C#

Coming from JS/PHP/Node background, somewhat new to C# app dev. Working on an MVC app.

I need to return an object of

IEnumerable<Car>
to my controller from my service. My service calls my repository which returns
IEnumberable<CarEntity>


I cannot figure out how to convert a list of
CarEntity
to a list of
Car
.

Car looks like

public int CarId { get; set; }
public string CarColor { get; set; }
public string CarMake { get; set; }
public string CarModel { get; set; }


and CarEntity looks like

public int Id { get; set; }
public string Color { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public string SomeOtherProp { get; set;}


This is an example but this is generally what I need. Do I need to do some sort of loop through my CarEntity list and push each one to the Car list? I would think there's some more astute way of doing this.

Answer

Yes. You need to create a new Car object for each item in the car entity list collection and assign property values. You can do that in a foreach loop

var carEntityList= new List<CarEntity>(); //assume this has items
var carList = new List<Car>();
foreach(car carEntity in carEntityList)
{
  var c= new Car();
  c.Id =carEntity.Id;
  // to do : Map other property values as well.
  carList.Add(c);     
}

Or Using handy LINQ extension methods such as IEnumerable.Select

var carEntityList= new List<CarEntity>(); //assume this has items
var carList = carEntityList.Select(s=>new Car { 
                                                Id = s.Id, 
                                                Color = s.Color, 
                                                Model = s.Model,
                                                Make = s.Make
                                              }
                                  );
Comments