字符串 string info= “桃子*3,李子*2,葡萄*3,李子*3,葡萄*2,桃子*4”怎麼把相同的合並在一起啊
C#
using System;
using System.Linq;
public class Test
{
public static void Main()
{
// your code goes here
string info="桃子*3,李子*2,葡萄*3,李子*3,葡萄*2,桃子*4";
info = string.Join(",", info.Split(',').GroupBy(x => x.Split('*')[0]).Select(x => x.Key + "*" + x.Sum(y => int.Parse(y.Split('*')[1]))));
Console.WriteLine(info);
}
}
在線驗證
http://ideone.com/9KjtW2
桃子*7,李子*5,葡萄*5