Beh, mi piacerebbe fare qualcosa di simile:
public sealed class Range
{
public int Low { get; private set; }
public int High { get; private set; }
public Range(int low, int high)
{
this.Low = low;
this.High = high;
}
}
Poi (completamente testato, non può anche compilare, ma spero che si otterrà la deriva):
public static IEnumerable<Range> FindRanges(IEnumerable<int> values)
{
using (IEnumerator<int> iterator = values.GetEnumerator())
{
if (!iterator.MoveNext())
{
yield break;
}
int low = iterator.Current;
int high = low;
while (iterator.MoveNext())
{
int next = iterator.Current;
if (next > high + 1)
{
// Previous range (or possibly single value) has finished
yield return new Range(low, high);
low = next;
}
high = next;
}
// Yield trailing range
yield return new Range(low, high);
}
}
Non penso che questo sia particolarmente facile da usare usando LINQ diretto, per essere onesti.
EDIT: Per adattare questo, ora che tutto comincia con H, basta usare:
var numbers = strings.Select(x => int.Parse(x.Substring(1));
var ranges = FindRanges(numbers);
var rangeStrings = ranges.Select(r => r.High == r.Low
? "H" + r.Low : "H" + r.Low + "-" + r.High);
var result = string.Join(",", rangeStrings);
fonte
2010-09-21 16:12:56
Do deve essere con LINQ? –
Che cos'è quell'insieme di numeri? Una stringa? Un array? –
Sono aperto a qualsiasi soluzione. è un insieme di banconote per essere esatti come H272 per il conto della casa 272, ma essenzialmente un insieme di stringhe – Jesse