如何搜索在KeyValuePair列表重复键,删除先前键值 [英] How to search duplicated key in KeyValuePair list and delete the earlier key value

查看:905
本文介绍了如何搜索在KeyValuePair列表重复键,删除先前键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 KeyValuePair <​​/ code>列表用来保存传入消息的一些信息。

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));

在消息进来,消息的参考ID作为存储密钥和消息的选择的值存储为列表中的值。如何检测当场重复键和删除列表中较早的一个?

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?

推荐答案

如果你不想重复,你可以使用词典&LT; TKEY的,TValue&GT; ,和检查是否存在密钥使用 的containsKey

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
}

或者,如果你不关心previous项目,你可以简单地替换它:

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

infoById[someId] = value;

这篇关于如何搜索在KeyValuePair列表重复键,删除先前键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆