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

 ̄綄美尐妖づ 提交于 2020-06-27 08:30:10

问题


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?

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!


回答1:


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);



回答2:


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




回答3:


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);



回答4:


Why not:

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

EDIT:

And next if you want to have an array of int:

int[] array = items.ToArray();



回答5:


I don't see why you use a String converted into an Array converted into a String..? Could this be what you need?

string finalList = activeList + "," + ddlDisabledTypes.SelectedValue;



回答6:


Why not just add the item as string directly?

string finalList = items + "," + itemToAdd;

int is automatically converted to string in concatenations.

if items can be null or empty then change the expression to

string finalList = String.IsNullOrEmpty(items) ? 
                     itemToAdd.ToString() : items + "," + itemToAdd;



回答7:


I use 'union' to create a new array, in this case the new element is at beginning:

class HelperX {
    /// <summary>
    /// Tenemos varios campos tipo bandera, cuyo valor puede ser 'S' = Sí o 'N' = No
    /// </summary>
    static public KeyValuePair<string, string>[] SiNo
    {
        get
        {
            return new KeyValuePair<string, string>[]
            {
                new KeyValuePair<string, string>( "S", "Sí"),
                new KeyValuePair<string, string>( "N", "No")
            };
        }
    }

    /// <summary>
    /// Tenemos varios campos tipo bandera, cuyo valor puede ser 'T' = 'Todos', 'S' = Sí o 'N' = No
    /// </summary>
    static public KeyValuePair<string, string>[] SiNoTodos
    {
        get
        {
            var todos = new KeyValuePair<string, string>[]
            {
                new KeyValuePair<string, string>( "T", "Todos"),
            }.Union(SiNo);

            return todos.ToArray();
        }
    }
}

Additionally, I can create a selectListItem to display them as select option in the View:

ViewBag.SeleccionSiNoTodos = HelperX.SiNoTodos
  .Select(kv => new SelectListItem() { 
          Value = kv.Key, 
          Text = kv.Value, 
          Selected = seleccionados?.Contains(kv.Key) == true })
  .ToList();

Finally, within a view I can get a Select option list by using:

@Html.DropDownList("SeleccionSiNoTodos", (IEnumerable<SelectListItem>)ViewBag.SeleccionSiNoTodos)


来源:https://stackoverflow.com/questions/9928378/c-sharp-linq-append-an-item-to-the-end-of-an-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!