Search code examples
c#asp.net-mvclinqlinq-to-entities

Convert IEnumerable to another IEnumerable C#


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

I need to return an object of IEnumerable<Car> to my controller from my service. My service calls my repository which returns IEnumerable<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.


Solution

  • 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.CarId =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 { 
                                                    CarId = s.Id, 
                                                    CarColor = s.Color, 
                                                    CarModel = s.Model,
                                                    CarMake = s.Make
                                                  }
                                      );