Skip to content

Instantly share code, notes, and snippets.

@kamiyaowl kamiyaowl/Extension.cs
Last active Aug 29, 2015

Embed
What would you like to do?
連続する数値を識別
[TestFixture]
static class Extensions {
public static string RangeString(this IEnumerable<int> src) {
var grouped = src.RangeGroup()
.Select(x => x.Item1 == x.Item2 ?
x.Item1.ToString() :
string.Format("{0} ... {1}", x.Item1, x.Item2));
var create = grouped.Aggregate("", (s, x) => string.Format("{0}{1},", s, x));
return create.Substring(0, create.Length - 1);//deliminator
}
/// <summary>
/// 連続する数値の開始と終了の数値のタプルを返します
/// </summary>
/// <param name="src"></param>
/// <returns></returns>
public static IEnumerable<Tuple<int, int>> RangeGroup(this IEnumerable<int> src) {
int start = int.MinValue;
int recent = int.MinValue;
foreach (var ch in src.OrderBy(x => x).Distinct()) {
if (start == int.MinValue) {
//開始点
start = ch;
recent = ch;
} else if (recent == ch - 1) {
//中間
recent = ch;
} else {
//終点
yield return new Tuple<int, int>(start, recent);
start = ch;
recent = ch;
}
}
yield return new Tuple<int, int>(start, recent);
}
[Test]
public static void RangeStringTest() {
var str = new[] { 1, 5, 6, 7, 10, 15, 16, 17, 18, 19 }.ChannelString();
Console.WriteLine(str);
Assert.AreEqual("1,5 ... 7,10,15 ... 19", str);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.