使用 IEnumerable<T> 在 .net core 中添加一个对象的实例

Using IEnumerable<T> to add instances of an object in .net core

我需要向 IEnumerable 添加一个对象,但不是 100% 确定如何操作。在我的 .net core 3.1 代码中,.add 似乎不适合我。

第一个class是这样的:

 public class ContainerA
{
    public string TestA { get; set; }

    public IEnumerable<ContainerB> Containers { get; set; }
}

然后是ContainerB class:

public class ContainerB
{
    public string TextString { get; set; }
}

我不确定如何将对象 ContainerB 的一堆 Continers 添加到 ContainerA 的实例对象中,如下所示:

var contA = new ContainerA();

contA.TestA = "works fine";

// Issues here and how to get lots of ContainerB.TestString into the contA instance.

感谢您的帮助。

IEnumerable不支持加法,如果想加法可以用IList or ICollection for Containers property type. If you want to stick with IEnumerable - you can create new one via Concat (or Append加单个元素)赋值给Containers:

IEnumerable<ContainerB> toAdd = ...; //  lots of ContainerB.TestString
contA.Containers = contA.Containers
    .Concat(toAdd);