Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and remove items from array in c#

Tags:

arrays

c#

I have a string array. I need to remove some items from that array. but I don't know the index of the items that need removing.

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

I need to remove the " " items. ie after removing " " my result should be arr={"a","b","c","d","e","f"}

how can I do this?

like image 307
Nelson T Joseph Avatar asked Feb 21 '12 10:02

Nelson T Joseph


2 Answers

  string[] arr = {" ", "a", "b", " ", "c", " ", "d", " ", "e", "f", " ", " "};
  arr = arr.Where(s => s != " ").ToArray();
like image 125
BlueM Avatar answered Nov 03 '22 07:11

BlueM


This will remove all entries that is null, empty, or just whitespaces:

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

If for some reason you only want to remove the entries with just one whitespace like in your example, you can modify it like this:

arr.Where( s => s != " ").ToArray();
like image 25
Øyvind Bråthen Avatar answered Nov 03 '22 05:11

Øyvind Bråthen