This is a human-readable serialization syntax of integer array.
The serialized string implies some integers, the consistent integers will be compressed with {start}-{end}
, and the "unconsistent" elements will be split by comma.
Now, I want to serialize a sorted int[]
to the string
, and deserialize a string
to the int[]
.
How can I achieve it concisely?
This is a related question: Split a List<int> into groups of consecutive numbers
I have an imperfect solution to serialize:
public string SerializationTest()
{
var weeks = new[] { 1, 2, 3, 5, 8, 9 };
return string.Join(", ", weeks
.Select((e, i) => (e, i))
.GroupBy(t => t.i - t.e)
.Select(tg => tg.Select(t => t.e).ToArray())
.Select(group => group.Length > 1 ? $"{group.First()}-{group.Last()}" : $"{group.Single()}"));
}
But there is no idea about deserialization, except switch every character.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…