gpt4 book ai didi

c# - 如何在KeyValuePair列表中搜索重复键并删除较早的键值

转载 作者:太空宇宙 更新时间:2023-11-03 21:18:44 25 4
gpt4 key购买 nike

我有一个 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;

关于c# - 如何在KeyValuePair列表中搜索重复键并删除较早的键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32242526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com