开发者

Removing strings from array C#

Is there a function to remove the last cell from array?

it's a string arr开发者_高级运维ay like: {"a","b","c",""}.


The length of an array is immutable, but you can create a new array without the empty "" strings:

string[] newArray = myArray.Where(str => str != "").ToArray();


Erm... just resize it

 Array.Resize(ref theArray, theArray.Length -1);

From the docs

public static void Resize(ref T[] array, int newSize)


If it's an array of strings, you can do something like:

 string[] results = theArray.Where(s => !string.IsNullOrWhitespace(s)).ToArray();

If you are just going to iterate the results, there's no need to convert back into an array, and you can leave off the .ToArray() at the end.


Edit:

If you just want to remove the last cell, and not empty entries (as suggested by your edited version), you can do this using Array.Copy more efficiently than using the LINQ statement above:

  string[] results = new string[theArray.Length - 1];
  Array.Copy( theArray, results, results.Length );


An array is a fixed-size collection object. That makes it woefully inadequate for what you want to do. The best you could do is create another one with one less element. That's expensive.

Fix the real problem, this should be a List<string>, now it's simple.


var newArraySize = oldArray.Length - 1;
var newArray = new string[newArraySize];
Array.Copy(oldArray, newArray, newArraySize);


  1. Create new array equal to existing array size -1
  2. aNewArray = aOldArray

Ofcourse you could just null the last element in your array, but that would result in problems later. Otherwise, use a nice flexible list.


If you always want to get rid of the last element,

        int[] a = new[] {1, 2, 3, 4, 5};
        int[] b = new int[a.Length - 1];
        Array.Copy(a, b, a.Length - 1);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜