问题
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