Home > Software design >  How to write better code for several for each loops in c# / ASP.NET / EF Core
How to write better code for several for each loops in c# / ASP.NET / EF Core

Time:12-23

i want to know how to write a better code then the below. It works, but i think there has to be a better way to write it. Maybe with some Lambda expressions ?

`

var dataList = new List<MyModel>();

        foreach (var data in dataArray)
        {
            var model = new MyModel();
            model.Name = data.Name;
            model.LastName = data.LastName;
            
            model.Model = "";
            model.SubModel = "";

            if (data.Cars.Any())
            {
                foreach (var car in data.Cars)
                {
                    model = new MyModel();
                    model.Name = data.Name;
                    model.LastName = data.LastName;
                    model.Model = car.Model;
                    model.SubModel = "";

                    if (car.SubModels.Any())
                    {
                        foreach (var subModel in car.SubModels)
                        {
                            model = new MyModel();
                            model.Name = data.Name;
                            model.LastName = data.LastName;
                            model.Model = car.Model;
                            model.SubModel = subModel.Model;
                            dataList.Add(model);
                        }
                    }
                    else
                    {
                        dataList.Add(model);
                    }
                }
            }
            else
            {
                dataList.Add(model);
            }
        }

`

Tried to convert it to Lync in VS

CodePudding user response:

pseudo code not tested. You need also three constructors to create the model class. Or you do it with property init:

new Model() { Name = data.Name, 
LastName = data.LastName, Model = car.Model, SubModel = subModel.Model}
        var dataList = dataArray
          .Select(item => item.Cars)
              .Select(car => new Model(data.Name,data.LastName,car.Model,subModel.Model))
          .Concat(item => item.SubModel
                    .Select(subModel => new Model(data.Name,data.LastName,car.Model,subModel.Model,subModel.Model)))
          .Concat(dataArray.Select(data => new Model(data.Name,data.LastName)))
  • Related