Skip to contentSkip to author details


A 1-post collection

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

Written by Michael Earls
 .NET  C#  Refactoring

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

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

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 accessoryGroupsList = new List(); 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) { accessoryGroupsList.Add(accessoryGroup); } } 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? :)