我有一份清单keyvaluepair<string, int>.
当我添加到列表中时,我检查密钥是否已经存在,我将值的计数增加到+1.如果没有,我添加新的(键,1).这就是我现在这样做的方式.有没有更好,更好的方法来做到这一点.我是LINQ的新手,但非常喜欢它.
IEnumerable<KeyValuePair<string, int>> kvp = myList.Where(x => x.Key.ToLower() == name.ToLower());
if (kvp == null || kvp.Count() == 0)
{
//Add first occurence
myList.Add(new KeyValuePair<string, int>(name, 1));
}
else
{
//Update occurence count +1 and add the new key
//TODO : Refactor
KeyValuePair<string, int> updatedKVP = new KeyValuePair<string, int>(name, kvp.FirstOrDefault().Value + 1);
myList.Remove(kvp.FirstOrDefault());
myList.Add(updatedKVP);
}
Run Code Online (Sandbox Code Playgroud)
谢谢.
听起来你因为区分大小写而保留了kvps列表.
这是另一种选择:
var dict = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
if(dict.ContainsKey(name))
{
dict[name] += 1;
}
else
{
dict[name] = 1;
}
Run Code Online (Sandbox Code Playgroud)