Skip to content

Instantly share code, notes, and snippets.

@fredyfx
Last active April 11, 2018 00:04
Show Gist options
  • Save fredyfx/1492125585a0332b7687ad1cc1453fee to your computer and use it in GitHub Desktop.
Save fredyfx/1492125585a0332b7687ad1cc1453fee to your computer and use it in GitHub Desktop.
C# parsing page-number strings. Esto retorna: Hello World 1 2 3 4 3 5 6 7 8 9 10 12
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
var result = GetNumbers("1-4,3,5-10,12");
foreach (var item in result){
Console.WriteLine(item);
}
}
public static IEnumerable<int> GetNumbers(string pagesToExtract){
foreach( string s in pagesToExtract.Split(',') )
{
// try and get the number
int num;
if( int.TryParse( s, out num ) )
{
yield return num;
continue; // skip the rest
}
// otherwise we might have a range
// split on the range delimiter
string[] subs = s.Split('-');
int start, end;
// now see if we can parse a start and end
if( subs.Length > 1 &&
int.TryParse(subs[0], out start) &&
int.TryParse(subs[1], out end) &&
end >= start )
{
// create a range between the two values
int rangeLength = end - start + 1;
foreach(int i in Enumerable.Range(start, rangeLength))
{
yield return i;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment