How to search duplicated key in KeyValuePair list and delete the earlier key value

有些话、适合烂在心里 提交于 2020-01-16 00:36:07

问题


I've a KeyValuePair list use to store some info from incoming message.

List<KeyValuePair<int, string>> qInfoTempList = new List<KeyValuePair<int, string>>();

qInfoTempList.Add(new KeyValuePair<int, string>(eventInfo.ReferenceId, eventInfo.StringValue));

Once the messages come in, the message's reference id stores as key and the message's selected value stores as value in the list. How can I detect a duplicated key on the spot and delete the earlier one in the list?

In this case, is it better to use Dictionary instead of List?


回答1:


If you don't want duplicates, you can use a Dictionary<TKey, TValue>, and check if the key exists using ContainsKey:

var infoById = new Dictionary<int, string>();
if (infoById.ContainsKey(someId))
{
    // Do override logic here
}

Or if you don't care about the previous item, you can simply replace it:

infoById[someId] = value;


来源:https://stackoverflow.com/questions/32242526/how-to-search-duplicated-key-in-keyvaluepair-list-and-delete-the-earlier-key-val

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!