110,552
社区成员
发帖
与我相关
我的任务
分享
public class MString
{
//data container
private Dictionary<string, int> _dictItem = null;
public MString() : this(null) { }
public MString(string data)
{
_dictItem = new Dictionary<string, int>();
if (!String.IsNullOrWhiteSpace(data))
{
//split
var arrPolyItem = data.Split(new char[] { '+' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in arrPolyItem)
{
var arrOneItem = item.Split(new char[] { '*' }, StringSplitOptions.RemoveEmptyEntries);
int count = arrOneItem.Length == 2 ? int.Parse(arrOneItem[1]) : 1;
if (count == 0)
continue;
Add(arrOneItem[0], count);
}
}
}
//add an item
public void Add(string key, int count = 1)
{
if (_dictItem.ContainsKey(key))
{
_dictItem[key] += count;
}
else
{
_dictItem.Add(key, count);
}
}
//remove an item
public void Remove(string key)
{
if (!_dictItem.ContainsKey(key))
return;
var count = _dictItem[key];
count--;
if (count == 0)
{
_dictItem.Remove(key);
}
else
{
_dictItem[key] = count;
}
}
public override string ToString()
{
string strResult = String.Empty;
foreach (var item in _dictItem)
{
strResult += "+" + item.Key + (item.Value == 1 ? "" : "*"+item.Value);
}
return strResult.Substring(1);
}
}
调用:
MString mstring = new MString("ABC+BB*2+CC*4");
mstring.Add("ABC");
mstring.Add("BB");
mstring.Remove("ABC");
mstring.Remove("BB");
string result = mstring.ToString(); //ABC+BB*2+CC*4
var dic = "ABC+BB*2+CC*4".Split('+').Select(s =>
{
var arr = s.Split('*');
return arr;
}).ToDictionary(k => k[0], v => v.Length > 1 ? int.Parse(v[1]) : 1);
foreach (var kv in dic)
{
Console.WriteLine(kv.Key + " " + kv.Value);
}
List<string> list = new List<string>(){"ABC","BB","BB","CC","CC","CC","CC"}
这样无论你怎么操作,只是修改这个list集合,最后再group by下之后string.join合并成一个字符串