0

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.

cdub
  • 24,555
  • 57
  • 174
  • 303
  • 1
    Use the `.Concat` or `.Append` extension methods. – Dai Jul 01 '20 at 19:28
  • The exact duplciate [How can I add an item to a IEnumerable collection?](https://stackoverflow.com/questions/1210295/how-can-i-add-an-item-to-a-ienumerablet-collection) as well as [Adding an item to IEnumerable](https://stackoverflow.com/questions/5026483/adding-an-item-to-ienumerable) – Pavel Anikhouski Jul 01 '20 at 20:37

1 Answers1

2

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);
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • 1
    @cdub I think they might have possibly fixed this in .NET Core, but at least with .NET Framework, always be careful when using `IList` this way. It *should* work...but at least in .NET Framework, arrays implemented `IList`, but then they throw exceptions if you use things like `IList.Add`. That doesn't mean `IList` shouldn't be used this way; it *should*. Just be cautious that it's not implemented by an array, because of a design decision made way back when. – Panzercrisis Jul 01 '20 at 19:37