gpt4 book ai didi

c# - 检测连续整数并折叠为字符串

转载 作者:行者123 更新时间:2023-12-03 23:26:38 26 4
gpt4 key购买 nike

免责声明:A very similar question was already asked in a Python context here.这是关于 C# 的。
我有一个包含整数的枚举,例如:

[1, 2, 3, 4, 7, 8, 10, 11, 12, 13, 14]
我想获得一个字符串,列出连续整数的范围:
1-4, 7-8, 10-14
我想出了:
public static void Main()
{
System.Diagnostics.Debug.WriteLine(FindConsecutiveNumbers(new int[] { 1,2, 7,8,9, 12, 15, 20,21 }));
}

private static string FindConsecutiveNumbers(IEnumerable<int> numbers)
{
var sb = new StringBuilder();
int? start = null;
int? lastNumber = null;
const string s = ", ";
const string c = "-";

var numbersPlusIntMax = numbers.ToList();
numbersPlusIntMax.Add(int.MaxValue);
foreach (var number in numbersPlusIntMax)
{
var isConsecutive = lastNumber != null && lastNumber + 1 == number;
if (!isConsecutive)
{
if (start != null)
{
if (sb.Length > 0) { sb.Append(s); }
if (start == lastNumber)
{
sb.Append(start); ;
}
else
{
sb.Append(start + c + lastNumber); ;
}
}

start = number;
}

lastNumber = number;
}

return sb.ToString();
}
该算法适用于有序输入。是否有内置/LINQ/较短的 C# 方式来执行此操作?

最佳答案

int[] numbers = { 1, 2, 3, 4, 7, 8, 10, 11, 12, 13, 14 };

return string.Join(", ",
numbers
.Select((n, i) => new { value = n, group = n - i })
.GroupBy(o => o.group)
.Select(g => g.First().value + "-" + g.Last().value)
);

关于c# - 检测连续整数并折叠为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63593303/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com