我有一个可能看起来像这样的字符串:“3, 7, 12-14, 1, 5-6”
我需要做的是将其更改为如下所示的字符串:“1, 3, 5, 6, 7, 12, 13, 14”
我已经使以下代码工作,但我非常感谢帮助如何用更少的代码行以更清洁的方式做到这一点:
private string sortLanes(string lanesString)
{
List<string> sortedLanes = new List<string>();
if (lanesString.Contains(',') || lanesString.Contains('-'))
{
List<string> laneParts = lanesString.Split(',').ToList();
foreach (string lanePart in laneParts)
{
if (lanePart.Contains('-'))
{
int splitIndex = lanePart.IndexOf('-');
int lanePartLength = lanePart.Length;
int firstLane = Convert.ToInt32(lanePart.Substring(0, splitIndex));
int lastLane = Convert.ToInt32(lanePart.Substring(splitIndex + 1, lanePartLength - splitIndex - 1));
while (firstLane != lastLane)
{
sortedLanes.Add(firstLane.ToString().Trim());
firstLane++;
}
sortedLanes.Add(lastLane.ToString());
}
else
{
sortedLanes.Add(lanePart.Trim());
}
}
sortedLanes.Sort();
sortedLanes = sortedLanes.OrderBy(x => x.Length).ToList();
lanesString = "";
foreach (string lane in sortedLanes)
{
if (lanesString.Length == 0)
{
lanesString = lane;
}
else
{
lanesString = lanesString + ", " + lane;
}
}
}
else
{
return lanesString;
}
return lanesString;
}