Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

c# - Serialize/Deserialize with a specified syntax: {1, 2, 3, 5, 8, 9} <--> "1-3, 5, 8-9"

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Choosing whichever implementation from your previous question then:

var numbers = new[] { 1, 2, 3, 4, 6, 7, 9 };
var groups = numbers.GroupConsecutive();

var serialized = string.Join(", ", groups.Select(i => i.Skip(1).Any() ?
    $"{i.First()}-{i.Last()}" : $"{i.First()}"));

var deserialized = serialized.Split(new string[] { ", "}, StringSplitOptions.None)
                            .Select(i => i.Split('-').Select(s => int.Parse(s)).ToArray())
                            .SelectMany(i => i.Length == 1 ? i : Enumerable.Range(i[0], i[1] - i[0] + 1)).ToList();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...