Home > Software engineering >  Add items to array (C#)
Add items to array (C#)

Time:08-27

I got some newCity:

ObservCity newCity = new ObservCity ()
{
 id = localCityId,
 entries =  somecity.ToArray()
};

Now I load saved city:

ObservCity loadOldCity = await myService.loadCity(id);

How to add newCity.entries to loadOldCity.entries?

This don't work

newCity.entries.Concat(loadOldCity.entries);

//save newCity   loadOldCity 
myService.saveCity(newCity);

CodePudding user response:

You have not posted any class declarations, so I will take a guess and say entries is either an IEnumerable or an array, based on your current code. I will also assume the whole property is read-only. So you just create a new instance:

var updatedCity = new ObservCity
{
 id = localCityId,
 entries = newCity.entries.Concat(loadOldCity.entries).ToArray()
};

myService.saveCity(updatedCity);

CodePudding user response:

You can add a range of items with the AddRange() method.

newCity.entries.AddRange(loadOldCity?.entries);
  • Related