使用指定的语法进行序列化/反序列化:{1、2、3、5、8、9}<-> "1-3、5、8-9"表示“ [英] Serialize/Deserialize with a specified syntax: {1, 2, 3, 5, 8, 9} <--> "1-3, 5, 8-9"

查看:68
本文介绍了使用指定的语法进行序列化/反序列化:{1、2、3、5、8、9}<-> "1-3、5、8-9"表示“的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是整数数组的一种易于理解的序列化语法.

This is a human-readable serialization syntax of integer array.

序列化的字符串包含一些整数,一致的整数将用{start}-{end}压缩,而不一致"的元素将以逗号分隔.

The serialized string implies some integers, the consistent integers will be compressed with {start}-{end}, and the "unconsistent" elements will be split by comma.

现在,我想将已排序的int[]序列化为string,并反序列化stringint[].

Now, I want to serialize a sorted int[] to the string, and deserialize a string to the int[].

我如何简洁地实现它?

这是一个相关的问题:拆分列表< int>分成连续的数字

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.

推荐答案

从您的上一个问题中选择哪种实现,然后:

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();

这篇关于使用指定的语法进行序列化/反序列化:{1、2、3、5、8、9}&lt;-&gt; "1-3、5、8-9"表示“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆