在实例化内部调用Add

我强烈怀疑此问题的答案是使用foreach方法,但我想看看是否存在我不知道的C#区域。

我具有(访问)以下课程(即我不能更改它):

public class Class1
{
    public string Name { get; set; }
    public List<string> Data { get; }
}

我试图循环填充该类。我有很多数据,而且它经常发生,因此速度是主要因素。我正在探索替换的想法:

foreach (var data in dataList)
{
    var newClass1 = new Class1();
    newClass1.Name = data.Name;
    newClass1.Data.AddRange(data.Info.List.Select(x => x.Id));

    NewList.Add(newClass1);
}

用这样的东西:

MyList.AddRange(dataList.Select(x => new Class1()
{
    Name = x.Name,
    Data = x.Info.List.Select(d => d.Id)
}));

The problem that I have is that Data is ReadOnly, so I can't assign a new list to it. Since I can't change the list, and I can't change Class1, are there any other options open to me (other than the original foreach loop)?

评论