【问题标题】:Sort data within string value对字符串值内的数据进行排序
【发布时间】:2017-01-09 10:18:12
【问题描述】:

包含特定格式的日期和整数的字符串:MM/dd/yyyy (Number)

string strData = "01/23/2017 (5); 01/16/2017 (2);01/24/2017 (6);01/16/2017 (5);01/23/2017 (10)";

基于以上,我想要以下:

  1. 如果日期相似,请添加数字
  2. 应按日期排序,即升序

预期输出

strData = "01/16/2017 (7);01/23/2017 (15);01/24/2017 (6)";    

我知道这是可能的,如果我们根据分号进行拆分,然后使用“for-loop”遍历值。

但请建议我 linq 解决方案。

【问题讨论】:

  • 而且对于 Linq,我很确定您需要拆分分号才能从该字符串中获得任何意义
  • 你能给我第 1 点的样本数据吗?
  • 加号是什么意思?
  • @derloopkat 如果日期相同,他想在日期后面加上括号中的数字,基本上是一组元素
  • @MongZhu 是对的。如果日期相同,我想在括号中添加数字。

标签: c# string linq sorting date-format


【解决方案1】:

这应该可行:

var elems = strData.Split(';') // First, split on semicolon
  .Select(s => s.Trim().Split(' ')) // then remove the extra space at the end of each element, and split again on the space
  .Select(s => new { d = DateTime.ParseExact(s[0], "MM/dd/yyyy", CultureInfo.InvariantCulture), n = int.Parse(s[1].Replace("(", "").Replace(")", "")) }) // here, we create a temp object containing the parsed date and the value
  .GroupBy(o => o.d) // group by date
  .OrderBy(g => g.Key) // then sort
  .Select(g => $"{g.Key:MM'/'dd'/'yyyy} ({g.Sum(a => a.n)})"); // and finally build the resulting string

然后您可以使用以下命令构建最终字符串:

string.Join(";", elems);

此答案使用 C# 6 插值字符串。如果使用旧版本的语言,请将 $"{g.Key:MM'/'dd'/'yyyy} ({g.Sum(a => a.n)})" 替换为 string.Format("{0:MM'/'dd'/'yyyy} ({1})", g.Key, g.Sum(a => a.n))

【讨论】:

    【解决方案2】:

    这是另一种方法

    string strData = "01/23/2017 (5); 01/16/2017 (2);01/24/2017 (6);01/16/2017 (5);01/23/2017 (10)";
    string result = string.Join(";", strData.Split(';')
              .Select(x => new { 
                  Date = DateTime.ParseExact(x.Trim().Split()[0], "MM/dd/yyyy", CultureInfo.InvariantCulture), 
                  Count = int.Parse(x.Trim().Split()[1].Trim('(', ')')) })
              .GroupBy(x => x.Date)
              .OrderBy(x => x.Key)
              .Select(x => x.Key.ToString("MM/dd/yyyy") + " (" + x.Sum(y => y.Count) + ")")); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-19
      • 2014-10-28
      • 2012-11-14
      • 2018-02-28
      • 2021-10-30
      • 2011-10-07
      • 1970-01-01
      相关资源
      最近更新 更多