Removing strings from a C # array

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

this is a string array like: {"a","b","c",""} .

+4
source share
7 answers

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

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

Erm ... just resize it

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

From the documents

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

+8
source

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 over the results, there is no need to convert back to an array, and you can leave .ToArray() at the end.


Edit:

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

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

An array is a collection object of a fixed size. This makes it extremely inadequate for what you want to do. The best thing you could do is create another element with one smaller element. It is expensive.

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

+5
source
 var newArraySize = oldArray.Length - 1; var newArray = new string[newArraySize]; Array.Copy(oldArray, newArray, newArraySize); 
+2
source
  • Create a new array equal to the size of the existing array -1
  • aNewArray = aOldArray

Of course, you can simply remove the last element in your array, but this will lead to problems later. Otherwise, use a good flexible list.

0
source

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
source

Source: https://habr.com/ru/post/1346125/


All Articles