我有一个 KeyValuePair
列表用于存储来自传入消息的一些信息。
List<KeyValuePair<int, string>> qInfoTempList = new List<KeyValuePair<int, string>>();
qInfoTempList.Add(new KeyValuePair<int, string>(eventInfo.ReferenceId, eventInfo.StringValue));
一旦消息进来,消息的引用 id 存储为键,消息的选定值存储为列表中的值。我如何当场检测到重复的 key 并删除列表中较早的 key ?
在这种情况下,使用 Dictionary
而不是 List
更好吗?
如果你不想重复,你可以使用 Dictionary<TKey, TValue>
,并使用 ContainsKey
检查 key 是否存在:
var infoById = new Dictionary<int, string>();
if (infoById.ContainsKey(someId))
{
// Do override logic here
}
或者如果你不关心前面的项目,你可以简单地替换它:
infoById[someId] = value;
我是一名优秀的程序员,十分优秀!