Code Refactoring - Converting an array with blanks to a List in C#

Code Refactoring - Converting an array with blanks to a List in C#

Update: It seems I could have simply used StringSplitOptions.RemoveEmptyEntries:

userFunctions.AccessoryGroups = reader["AccessoryGroups"].ToString()
        .Trim().Split(new[] { "|" }, 

to reduce it to a single line of code.

I was writing some code the other day and I had the feeling that there was an easier way to do it. I was converting an array to a List, but I wanted to eliminate any blank strings, so I couldn’t just call myArray.ToList().

Old code:

List<string> accessoryGroupsList = new List<string>(); 
string accessoryGroups = reader["AccessoryGroups"].ToString(); 
string[] accessoryGroupsArray = accessoryGroups.Split('|'); 
foreach(string accessoryGroup in accessoryGroupsArray) 
    // get rid of any blank strings 
    if(accessoryGroup.Trim() != string.Empty) 
userFunctions.AccessoryGroups = accessoryGroupsList;

As you can see, that’s a lot of code. It just seemed like overkill to me, so I had to refactor.

Here’s the final code:

string[] accessoryGroups = reader["AccessoryGroups"].ToString().Trim().Split('|'); 
userFunctions.AccessoryGroups = accessoryGroups.Where(a => a.Trim() != string.Empty).ToList();

From 7 functional lines of code to 2. I’d say that’s an improvement. It also looks more elegant. And in the end, isn’t it all about elegant code? :)