Reputation: 4792
I have a bunch of strings I would like to parse that all look like this:
"1001, 1003, 1005-1010"
"1015"
"900-903"
"200, 202-209, 211-220"
Sometimes these strings will be just one integer, sometimes multiple separated by commas, and sometimes a range, and the latter two can appear simultaneously in a single string in any order.
What I would like to do is create a function that takes in the string and returns a collection of integers by parsing the string. So for example the first string should return:
[1001, 1003, 1005, 1006, 1007, 1008, 1009, 1010]
What are some smart ways to do this in .NET 4.0?
Upvotes: 1
Views: 719
Reputation: 54897
Traditional loop that might be easier to read:
string input = "1001, 1003, 1005-1010";
List<int> result = new List<int>();
foreach (string part in input.Split(','))
{
int i = part.IndexOf('-');
if (i == -1)
{
result.Add(int.Parse(part));
}
else
{
int min = int.Parse(part.Substring(0, i));
int max = int.Parse(part.Substring(i + 1));
result.AddRange(Enumerable.Range(min, max - min + 1));
}
}
Upvotes: 2
Reputation: 125640
.NET 4.0 means you got LINQ available, so you should probably use it:
var input = "1001, 1003, 1005-1010";
var results = (from x in input.Split(',')
let y = x.Split('-')
select y.Length == 1
? new[] { int.Parse(y[0]) }
: Enumerable.Range(int.Parse(y[0]), int.Parse(y[1]) - int.Parse(y[0]) + 1)
).SelectMany(x => x).ToList();
Upvotes: 3