序列和Rangify书籍索引列表

时间:2015-07-27 08:41:16

标签: c# sorting indexing

我为我的办公室项目编写了一个基于MS字的注册工具,其中应用程序将根据Nummer(标题编号,关键字和法律名称)执行复杂的SR,并为每个输入字文件创建一个寄存器。

目前,应用程序已编码且已完成90%,对于客户的最新更改请求,我需要将以下内容添加到应用程序中。

目前我有

等标题号列表
  

1,2,3,3.1,3.2,3.3,3.4,4,5,6,7.1.1,7.1.2,7.1.3

要求是按正确的顺序对它们进行升序排序,并Rangify近似数字。

例如,形成上述内容:

  

1,2,3

应该按照以下方式进行调整:

  

1-3

     

3.1,3.2,3.3,3.4

应该按照以下方式进行调整:

  

3.1-3.4

  

4,5,6

as

  

4-5

  

7.1.1,7.1.2,7.1.3

as

  

7.1.1-7.1.3

最终在上面的列表中,项目应按顺序进行排序,然后按照下面的方式进行测量:

  

1-3,3.1-3.4,4-6,7.1.1-7.1.3

我尝试按级别分隔项目,并将它们添加到排序列表并检查距离,并将它们放入一个测试范围,但这对我来说并不起作用)

然后通过一些谷歌搜索我发现了c#函数,但这个函数仅用于整数

IEnumerable<string> Rangify(IList<int> input) {
    for (int i = 0; i < input.Count; ) {
        var start = input[i];
        int size = 1;
        while (++i < input.Count && input[i] == start + size)
            size++;

        if (size == 1)
            yield return start.ToString();
        else if (size == 2) {
            yield return start.ToString();
            yield return (start + 1).ToString();
        } else if (size > 2)
            yield return start + " - " + (start + size - 1);
    }
}

所以有人可以指示我为此找到解决方案。

谢谢

1 个答案:

答案 0 :(得分:1)

您可以这样做:

    private static List<string> SortTitleNums(List<string> titleNums)
    {            
        // list that'll hold the result of current operation
        List<string> result = new List<string>();

        // sorts the input array
        titleNums.Sort();

        // field that will indicate start and end of a sequence
        bool sequenceStarted = false;

        for (int i = 0; i < titleNums.Count - 1; i++)
        {
            // checks if the value is greater than current value by 1 to find sequence
            if (Convert.ToInt32(titleNums[i + 1].Replace(".", "")) - Convert.ToInt32(titleNums[i].Replace(".", "")) == 1)

                // if sequence is found we add this value to the result list and change sequnceStarted field to true.
              { if (!sequenceStarted) { result.Add(titleNums[i] + "-"); sequenceStarted = true; } }

            // if sequence is found and next value does not refer to the sequence than we append the record with current value and change 
            //value for sequenceStarted field to false. If sequence not found than we just add the number.
            else if (sequenceStarted) { result[result.Count - 1] += titleNums[i]; sequenceStarted = false; } else result.Add(titleNums[i]);                
        }

        return result;
    }

使用示例:

    static void Main()
    {
        List<string> titleNums = new List<string>()
        {
            "1", "2", "6", "3", "3.1", "3.2", "3.3", "8", "7.1.1", "7.1.2", "8.1.1", "7.1.3", "7.2.1", 
        };

        titleNums = SortTitleNums(titleNums);

        foreach (var item in titleNums)
            Console.WriteLine(item);

        Console.ReadKey();
    }

输出:"1-3", "3.1-3.3", "6", "7.1.1-7.1.3", "7.2.1", "8"