Goal
Convert the following into an IEnumerable
of integers accounting for the x-y
ranges:
"1,2,3,0,7,8,9,10-15"
to
{ 1, 2, 3, 0, 7, 8, 9, 10, 11, 12, 13, 14, 15 }
Current implementation
I've written this little function and got something working, but I'm wondering if this can become more efficient or rich in features. My test cases all pass which cover positive and negative ranges.
public IEnumerable<int> GetRange(string numbers) {
string[] items = numbers.Split(',');
foreach (var item in items) {
if (!string.IsNullOrWhiteSpace(item)) {
//does it contain a -? it's a range then
int result;
if (item.Contains("-") && !item.EndsWith("-")) {
int start, end;
if (int.TryParse(item.Substring(0, item.IndexOf("-")), out start) && int.TryParse(item.Substring(item.IndexOf("-") + 1), out end)) {
int direction = start < end ? 1 : -1;
for (result = start; (direction == 1 ? result < end + direction : result > end + direction); result += direction)
yield return result;
continue;
}
}
if (int.TryParse(item, out result)) {
yield return result;
continue;
}
}
throw new InvalidCastException(string.Format("Unable to cast \"{0}\" to an int", item));
}
}