linq 如何在C# / ASP.NET/ EF Core中为多个for each循环编写更好的代码

vc6uscn9  于 2022-12-25  发布在  C#
关注(0)|答案(1)|浏览(143)

我想知道如何写一个比下面更好的代码。它工作,但我认为必须有一个更好的方式来写它。也许与一些Lambda表达式?
'

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

'
尝试在VS中将其转换为Lync

nue99wik

nue99wik1#

伪代码没有测试。你还需要三个构造函数来创建模型类。或者你用属性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)))

相关问题