2017-01-09 57 views
1

包含日期和整数在特定格式的字符串:MM/DD/YYYY(数目)排序数据

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循环”。

但请建议我linq解决方案。

+1

并且还使用LINQ我敢肯定,你需要分割的分号从字符串任何意义 – Steve

+0

你可以给我点1的样本数据吗? –

+0

添加数字是什么意思? – derloopkat

回答

5

这应该工作:

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插值字符串。如果使用该语言的旧版本,由string.Format("{0:MM'/'dd'/'yyyy} ({1})", g.Key, g.Sum(a => a.n))

2

这里更换$"{g.Key:MM'/'dd'/'yyyy} ({g.Sum(a => a.n)})"是另一种

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) + ")"));