Has*_*san 1 c# linq sorting string date-format
包含特定格式的日期和整数的字符串: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)";
Run Code Online (Sandbox Code Playgroud)
基于以上我想要以下内容:
预期产出:
strData = "01/16/2017 (7);01/23/2017 (15);01/24/2017 (6)";
Run Code Online (Sandbox Code Playgroud)
我知道有可能,如果我们在分号的基础上拆分,然后使用'for-loop'遍历值.
但请建议我linq解决方案.
这应该工作:
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
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用以下代码构建最终字符
string.Join(";", elems);
Run Code Online (Sandbox Code Playgroud)
这个答案使用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))