如何找到代表给定输入的范围?
例如:
:Entity(type)
更具体地说,如何在给定的整数列表中找到一组代表间隔的范围?
答案 0 :(得分:-2)
不久前我遇到了同样的问题,并找到了解决方法here
public static string GetRangeString(List<int> arr)
{
if (arr == null || !arr.Any()) return string.Empty;
if (arr.Count() == 1) return arr[0].ToString();
var rangeString = new StringBuilder();
bool isRange = false;
for (int i = 0; i < arr.Count; i++)
{
while (i < arr.Count - 1 && arr[i] + 1 == arr[i + 1])
{
if (!isRange) rangeString.Append($"{arr[i]}");
isRange = true;
i++;
}
if (isRange)
{
rangeString.Append("-");
isRange = false;
}
rangeString.Append($"{arr[i]},");
}
return rangeString.ToString().TrimEnd(',');
}
用法
string input = "1,6,3,8,7,12,16,15,13,9,2";
List<int> ungroupedList = new List<int>();
string[] parts = (input.Split(','));
foreach (string part in parts)
{
ungroupedList.Add(Convert.ToInt16(part));
}
ungroupedList.Sort();
string groupedString = GetRangeString(ungroupedList);
输出1-3,6-9,12-13,15-16