包含特定格式的日期和整数的字符串: 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)";
基于以上所述,我想要关注:
预期输出:
strData = "01/16/2017 (7);01/23/2017 (15);01/24/2017 (6)";
我知道有可能,如果我们在分号的基础上拆分,然后使用' for-loop'来遍历值。
但请建议我使用linq解决方案。
答案 0 :(得分: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插值字符串。如果使用该语言的旧版本,请将$"{g.Key:MM'/'dd'/'yyyy} ({g.Sum(a => a.n)})"
替换为string.Format("{0:MM'/'dd'/'yyyy} ({1})", g.Key, g.Sum(a => a.n))
答案 1 :(得分: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) + ")"));