C# LINQ append an item to the end of an array

Try items.Concat(new[] { itemToAdd });.


The easiest way is to change your expression around a bit. First convert to a List<int>, then add the element and then convert to an array.

List<int> items = activeList.Split(',').Select(n => Convert.ToInt32(n)).ToList();
int itemToAdd = ddlDisabledTypes.SelectedValue.ToInt(0);
items.Add(itemToAdd);

// If you want to see it as an actual array you can still use ToArray
int[] itemsAsArray = items.ToArray();

Based on your last line though it seems like you want to get all of the information back as a string value. If so then you can do the following

var builder = new StringBuilder();
foreach (var item in items) {
  if (builder.Length != 0) {
    builder.Append(",");
  }
  builder.Append(item);
}
string finalList = builder.ToString();

If the overall goal though is to just append one more item to the end of a string then it's much more efficient to do that directly instead of converting to an int collection and then back to a string.

int itemToAdd = ddlDisabledTypes.SelectedValue.ToInt(0);
string finalList = String.IsNullOrEmpty(activeList)
  ? itemToAdd.ToString()
  : String.Format("{0},{1}", activeList, itemToAdd);

Your example code seems really convoluted to match the conditions

using your code

List<int> items = activeList.Split(',').Select(n => Convert.ToInt32(n)).ToList();  
items.Add(ddlDisabledTypes.SelectedValue.ToInt(0));  

string finalList = String.Join(',',items.ToArray());

Just manipulating the string

int itemToAdd = ddlDisabledTypes.SelectedValue.ToInt(0);  
string finalList = String.IsNullOrWhiteSpace(activeList) ? 
                                           itemToAdd.ToString() :
                                           itemToAdd + string.format(",{0}",itemToAdd);

Tags:

C#

Linq