I have the following method that I created that works fine if the corresponding separator actually exists. I want to save this from LINQ for now ...
eg.
If I pass the line "123; 322; 323", it works fine.
But if I pass only one string value without a separator, such as "123", it is clearly not going to separate it, since there is no separator. I'm just trying to find the best way to check and consider this and be able to spit out this one value 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, it seems to work, but sure for a long time
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;
}
source
share