Find and remove items from an array in C #

I have a string array. I need to remove some elements from this array. but I don’t know the index of the items that need to be removed.

My array: string [] arr = {"," a "," b ",", "c", "," d ",", "e", "f", "", ""}.

I need to delete the elements ". Ie after deleting" "my result should be arr = {" a "," b "," c "," g "," d "," e "}

How can i do this?

+5
source share
4 answers
string[] arr = {" ", "a", "b", " ", "c", " ", "d", " ", "e", "f", " ", " "}; arr = arr.Where(s => s != " ").ToArray(); 
+10
source

This will delete all entries that are empty, empty or just spaces:

 arr.Where( s => !string.IsNullOrWhiteSpace(s)).ToArray(); 

If for some reason you want to delete entries with only one space, as in your example, you can change it as follows:

 arr.Where( s => s != " ").ToArray(); 
+6
source

Using LinQ

 using System.Linq; string[] arr= {" ","a","b"," ","c"," ","d"," ","e","f"," "," "}. arr.Where( x => !string.IsNullOrWhiteSpace(x)).ToArray(); 

or depending on how you fill the array, you can do this before

 string[] arr = stringToBeSplit.Split('/', StringSplitOptions.RemoveEmptyEntries); 

then empty records will not be placed in your string array first

+2
source

You can use except to remove an empty value

 string[] arr={" ","a","b"," ","c"," ","d"," ","e","f"," "," "}. arr= arr.Except(new List<string> { string.Empty }).ToArray(); 
0
source

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


All Articles