2 Lines of C# Code that replaced my bloated 44 lines - The Reductionist's View
Could you reduce my 44 lines down to just 2?
Sometimes as a developer you are humbled by something dumb that you did. I had written this huge, poorly designed piece of code that was supposed to remove blank strings that are in a relatively small array of strings. I felt smart and not smart at the same time. But the end result was good.
All I wanted to do is remove blank strings in an array of strings. That means if I had a string array of 35 with a 31 one of them blank, I just wanted that to be converted to a nice small 4 element string array with my data.
So I wrote this goofy piece of code. It was even named poorly.
Bloated Algorithm | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | public static string[] KillSingleBlanks(string[] arr) { // if find two blanks, copy one, next char, and skip all // if found one blank, copy current // int max_size = arr.Length; string[] new_arr = new string[max_size]; int src = 0; int trg = 0; int hdr_count = 0; while (src < max_size && (arr[src].Trim() == "" || arr[src] == null)) { src++; } while (src < max_size) { if (arr[src].Trim() == "" && arr[src + 1].Trim() == "") { // found 2 in a row, so copy one blank and skip to end //new_arr[trg++] = ""; while (src < max_size && arr[src].Trim() == "") { src++; } break; } else { // here because no two blanks in a row, so copy and advance if (arr[src] != "") { new_arr[trg++] = arr[src]; } src++; } } hdr_count = trg; while (src < max_size) { if (arr[src].Trim() != "") { new_arr[trg++] = arr[src]; } src++; } return new_arr; } |
How I ended up with two lines
Stop. Have you tried to find an answer yourself? Here it is ? two lines of code that do an infinitely better job at removing blank string entries.
The Reductionist's Algorithm | |
1 2 3 4 5 6 7 | public static string[] KillSingleBlanks(string[] arr) { var array = arr.Where(r=>!String.IsNullOrEmpty(r.Trim())); string[] str = array.ToArray<string>(); return str; } |
Follow up
Now I need to go for manual loops in arrays and then try to work with them as IEnumerables and collections that are processed with LINQ.