C # LINQ add element to end of array
I have an int [] array. I need to take an int and add it to the end of an array without affecting the position of other elements in that array. Using C # 4 and LINQ, what is the most elegant way to achieve this?
My code:
int[] items = activeList.Split(',').Select(n => Convert.ToInt32(n)).ToArray();
int itemToAdd = ddlDisabledTypes.SelectedValue.ToInt(0);
// Need final list as a string
string finalList = X
Thanks for any help!
source to share
The easiest way is to slightly change the expression. Convert to first List<int>
, then add element and then convert to 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, although it seems like you want to return all information as value string
. If so, 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 is to simply add another element to the end of the string, it is much more efficient to do so directly instead of converting to a collection int
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);
source to share
Your example code seems really convoluted to fit 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 manipulate the string
int itemToAdd = ddlDisabledTypes.SelectedValue.ToInt(0);
string finalList = String.IsNullOrWhiteSpace(activeList) ?
itemToAdd.ToString() :
itemToAdd + string.format(",{0}",itemToAdd);
source to share
Why not just add the element as string
directly?
string finalList = items + "," + itemToAdd;
int
automatically converted string
to concatenations.
if items
can be null
or empty then change the expression to
string finalList = String.IsNullOrEmpty(items) ?
itemToAdd.ToString() : items + "," + itemToAdd;
source to share