1

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?

YWah
  • 571
  • 13
  • 38

1 Answers1

4

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;
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • Hi @YuvalItzchakov, thanks for your fast response. So if I use Dictionary, will the size of the Dictionary keep increasing when the messages come in? The key will be duplicated after first run and new key will not be produced. – YWah Aug 27 '15 at 07:19
  • 1
    @YWah Yes, it will resize dynamically as you insert records. – Yuval Itzchakov Aug 27 '15 at 07:21