I’ve got the following method I created which works fine if there actually is the delimiter in question. I want to keep this out of LINQ for now…
e.g.
If I pass in the string “123;322;323” it works great.
But if I only pass in one string value without the delimiter such as “123” it obviously is not going to split it since there is no delimiter. I am just trying to figure out the best way to check and account for this and be able to spit out that one value back in the list
public static List<int> StringToList(string stringToSplit, char splitDelimiter)
{
List<int> list = new List<int>();
if (string.IsNullOrEmpty(stringToSplit))
return list;
string[] values = stringToSplit.Split(splitDelimiter);
if (values.Length < 1)
return list;
foreach (string s in values)
{
int i;
if (Int32.TryParse(s, out i))
list.Add(i);
}
return list;
}
UPDATED: This is what I came up with that seems to work but sure is long
public static List<int> StringToList(string stringToSplit, char splitDelimiter)
{
List<int> list = new IntList();
if (string.IsNullOrEmpty(stringToSplit))
return list;
if (stringToSplit.Contains(splitDelimiter.ToString()))
{
string[] values = stringToSplit.Split(splitDelimiter);
if (values.Length <= 1)
return list;
foreach (string s in values)
{
int i;
if (Int32.TryParse(s, out i))
list.Add(i);
}
}
else if (stringToSplit.Length > 0)
{
int i;
if(Int32.TryParse(stringToSplit, out i))
list.Add(i);
}
return list;
}
There are a LOT of unnecessary checks for conditions that don’t matter to the core logic of the method.
Try this. You hopefully have some unit tests calling this method to make sure it works…right?