Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34160

Adding items to sub-array of an array doesn't work

I have this class:

ActiveCampaign
{
     public Campaign campaign;
     public IEnumerable<CampaignView> Views;
}

ac is type of ActiveCampaign[]

The following code executes without any errors but nothing is added to its views. What amd I missing here?

ac.FirstOrDefault(a => a.Campaign.Id == c.Id).Views.ToList().Add(cv);

Upvotes: 1

Views: 75

Answers (2)

Jon Hanna
Jon Hanna

Reputation: 113282

You're creating a new list that is a copy of the Views property, then adding to it, then throwing that list away.

If you want to permanently affect Views then make it a List or IList type and add to it directly.

If you want to see the views plus that new item then get the list into a variable before the add, or use Concat (or even better Append though it's currently only available in dotnet core) to create an enumeration of the views items along with the addition.

Upvotes: 1

rory.ap
rory.ap

Reputation: 35290

When you call ToList() you're creating a separate list; you're not adding to ac. You need to assign the return value:

List<ActiveCampaign> newList = ac.FirstOrDefault(a => a.Campaign.Id == c.Id).Views.ToList();

and then you can use it...

newList.Add(cv);

Upvotes: 2

Related Questions