C#LINQ将项目追加到数组的末尾 [英] C# LINQ append an item to the end of an array

查看:70
本文介绍了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);

这篇关于C#LINQ将项目追加到数组的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆