Split numbers at nth occurrence in C#

class Program
{
static void Main(string[] args)
{

var finalResult = GetSplittedNumbers("1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30",10);
}
public static List<string> GetSplittedNumbers(string stringSeparatedByComma,int n)
{
var listOfSeparatedValues = new List<string>();
List<int> splittedIntArrays =
stringSeparatedByComma.Split(',').Select(
x => Convert.ToInt32(x)).ToList();
var splittedList = new List<int>();
foreach (int item in splittedIntArrays)
{

int status = item % n;
if (splittedList == null)
{
splittedList = new List<int>();
}

splittedList.Add(item);

if (status == 0)
{

string res = AgainCommaSeparated(splittedList);
listOfSeparatedValues.Add(res);
splittedList = null;
}
}
return listOfSeparatedValues;
}
private static string AgainCommaSeparated(IEnumerable<int> numbers )
{
var result= numbers.Aggregate("", (current, number) => current + number.ToString() + ",");
return result.Substring(0, result.Length - 1);
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s