0

我的意见是

string PageRange = "1,2-5,9";

我需要将它们转换成

string TotalRange = "1,2,3,4,5,9";

请分享你的想法。

4

3 回答 3

8

非 LINQ 解决方案:以下方法处理输入字符串并用数字序列替换范围:

static IEnumerable<int> RangeToSequence(string input)
{            
    string[] parts = input.Split(',');
    foreach (var part in parts)
    {
        if (!part.Contains('-')) // simple number, just return it
        {
            yield return Int32.Parse(part);
            continue;
        }
        // otherwise we have range
        string[] rangeParts = part.Split('-');
        int start = Int32.Parse(rangeParts[0]);
        int end = Int32.Parse(rangeParts[1]);

        while (start <= end)
        {
            yield return start; 
            start++;
        }
    }
}

您可以创建字符串:

var result = String.Join(",", RangeToSequence(PageRange));

Linq 解决方案:您可以将简单数字视为仅开始的范围。因此,您可以使用 SelectMany 从每个部分中选择范围:

var numbers = from part in PageRange.Split(',')
              let range = part.Split('-')
              let start = Int32.Parse(range[0])
              let end = Int32.Parse(range[range.Length - 1])
              from i in Enumerable.Range(start, end - start + 1)
              select i;

string result = String.Join(",", numbers);
于 2013-09-16T10:39:57.600 回答
0
            List<string> result = new List<string>();
            string PageRange = "1,2-5,9";
            var strings = PageRange.Split(',');
            foreach (var s in strings)
            {
                var split = s.Split('-');
                if (split.Count() == 1)
                {
                    result.Add(s);
                    continue;
                }

                for (int i = int.Parse(split[0]); i <= int.Parse(split[1]); i++)
                {
                    result.Add(i.ToString());
                }
            }
于 2013-09-16T10:42:50.090 回答
-1

尝试

var result = "";
var aray = PageRange.Split(',').ToArray();
foreach (var item in aray)
{
    if (item.IndexOf('-') != -1)
    {
        var splitparts = item.Split('-');
        result= Enumerable.Range(Convert.ToInt32(item.Split('-')[0]), (Convert.ToInt32(item.Split('-')[1]) - Convert.ToInt32(item.Split('-')[0]))).Aggregate((a, b) => a.ToString() + "," + b.ToString());
    }

    if (result.Equals(""))
    {
        result = item;
    }
    else
    {
        result += "," + item;
    }
}
于 2013-09-16T10:43:39.220 回答