I'm sure it is not best way but it is working, maybe it gives you a hint to fix it or find your own method;
First, let's fill list with dummy values;
List<string> list = new List<string>();
Enumerable.Range(0, 10).ToList().ForEach(p => list.Add("S1-00-" + (p + 220).ToString().PadLeft(4, '0')));
Enumerable.Range(0, 10).ToList().ForEach(p => list.Add("S1-00-" + p.ToString().PadLeft(4, '0')));
Enumerable.Range(0, 10).ToList().ForEach(p => list.Add("S1-00-" + (p+100).ToString().PadLeft(4, '0')));
Enumerable.Range(0, 10).ToList().ForEach(p => list.Add("S1-00-" + (p + 380).ToString().PadLeft(4, '0')));
Then we need to sort list with our method;
list.Sort((a, b) => ExtractNumber(a).CompareTo(ExtractNumber(b)));
var result = GetGroups(list).ToList();
Methods;
private int ExtractNumber(string text)
{
var asd = new string(text.Reverse().TakeWhile(char.IsDigit).Reverse().ToArray());
int result = 0;
int.TryParse(asd, out result);
return result;
}
private IEnumerable<IEnumerable><string>> GetGroups(List<string> list)
{
while (list.Any())
{
if (list.Count == 1)
{
var single = list;
list = list.Except(single).ToList();
yield return single;
}
else
{
var sequentialList = list.TakeWhile((a, b) => ExtractNumber(list[b + 1 >= list.Count ? b : b + 1]) - ExtractNumber(list[b]) == 1).ToList();
list = list.Except(sequentialList).ToList();
sequentialList = sequentialList.Concat(list.Take(1)).ToList();
list.RemoveAt(0);
yield return sequentialList;
}
}
}
If you notice any wrongs, please tell me.