C#LINQ将项目追加到数组的末尾
我有一个int []数组.我需要获取一个int并将其附加到数组的末尾,而不影响该数组中其他项目的位置.使用C#4和LINQ,最完美的方法是什么?
I have an int[] array. I need to take an int and append it to the end of the array without affecting the position of the other items in that array. Using C# 4 and LINQ what is the most elegant way to achieve this?
我的代码:
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
感谢您的帮助!
最简单的方法是稍微更改一下表达式.首先转换为List<int>
,然后添加元素,然后转换为数组.
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();
尽管您似乎想以string
值的形式返回所有信息,但还是基于最后一行.如果是这样,那么您可以执行以下
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();
但是,如果总体目标是在字符串的末尾追加一个项目,则直接执行此操作要比将其转换为int
集合然后再返回字符串的效率要高得多.
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);