I need to add an object to an IEnumerable but not 100% sure how to do it. It appears .add isn't working for me in my .net core 3.1 code.
The first class is this:
public class ContainerA
{
public string TestA { get; set; }
public IEnumerable<ContainerB> Containers { get; set; }
}
Then there is the ContainerB class:
public class ContainerB
{
public string TextString { get; set; }
}
I am unsure about how to add a bunch of Continers of object ContainerB to the instance object of ContainerA, like so:
var contA = new ContainerA();
contA.TestA = "works fine";
// Issues here and how to get lots of ContainerB.TestString into the contA instance.
Thanks for your help.
IEnumerable
does not support additions, if you want to able to add you can use IList
or ICollection
for Containers
property type. If you want to stick with IEnumerable
- you can create new one via Concat
(or Append
to add single element) and assign it to Containers
:
IEnumerable<ContainerB> toAdd = ...; // lots of ContainerB.TestString
contA.Containers = contA.Containers
.Concat(toAdd);