Freigeben über


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.

Comments

  • Anonymous
    June 18, 2014
    For me it seems your long code sample does something different than eliminating all empty lines. More like if it reduces more empty lines to a single one. Oh, and any Special reason you don't use String.IsNullOrWhitespace instead of trimming the string and using IsNullOrEmpty?

  • Anonymous
    June 19, 2014
    The comment has been removed

  • Anonymous
    June 19, 2014
    I don't understand, why is the first code that Long ?? u Need just to Loop and trim , and this is what ur linq query does!!

  • Anonymous
    June 19, 2014
    Your original code is too long and not readable. Sorry, it is horrible actually. You can accomplish what you wanted in a shorter and better way even without Linq. For example, you could just insert the not-empty strings to a new list and then call ToArray(). Just one small loop... var list = new List<string>(arr.Length); foreach(var item in arr)    if( String.IsNullOrWhiteSpace(item))              list.Add(item) return list.ToArray();

  • Anonymous
    June 20, 2014
    That was one of those routines that morphed over time, doing something different without refactoring. It was for a little utility that builds html tables with lines in the clipboard. Initially, it was calculating how many columns before it built the html table. Then that was done before the function, so that code just snuck through with me removing. I bet many readers have code they aren't proud of :-)

  • Anonymous
    June 24, 2014
    I shudder to think of the VB6 code I wrote back in the late 90's.

  • Anonymous
    June 24, 2014
    Indeed... return arr.Where(r=>!string.IsNullOrEmpty(r.Trim())).ToArray<string>();

  • Anonymous
    June 24, 2014
    It's a very rare occurrence when I look at old code that I wrote and think "this is an amazing piece of code". Usually, that last word is different. It's why whenever I have to look at someone else's code I don't judge them based on that code. If the code I write today was the same as the code I wrote five, two or even one year ago, I had learned nothing and made no progress. With your specific piece of code, I find I almost never use IsNullOrEmpty anymore. I have no use for strings that only have spaces in them and as others mentioned here, IsNullOrWhitespace does that trick for you. I assume performance wise it ends up doing the same thing, but at least your code is clearer

  • Anonymous
    June 24, 2014
    The comment has been removed

  • Anonymous
    June 25, 2014
    You could even go inline: array = array.Except(array.Where(String.IsNullOrWhiteSpace)).ToArray();

  • Anonymous
    August 24, 2014
    Reductionist? Shouldn't it be minimalist?