Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hey,

I am looking for a C# data structure that will allow me to store multiple values with the same key and then later on, look through the data structure and pull out the most recent entry for a given key.

I am planning on using an int value for the key and a custom object for the value. Is this possible?

Thanks
Posted

If you need to keep all of the values, but still be able to retrieve the most recent one for a given key, you could use a List or LinkedList to store all the values and a Dictionary to save the values for a given key, something like this:
public class DataStructure<br />{<br />  public void Add(int key,MyObject data)<br />  {<br />    DataList.AddTail(new Entry(key,data));<br />    DataDictionary[key] = data;<br />  }<br />  public MyObject Find(key)<br />  {<br />    MyObject data = null;<br />    DataDictionary.TryGetValue(key,out data);<br />    return data;<br />  }<br />  private class Entry<br />  {<br />    public Entry(int key,MyObject data)<br />    {<br />      Key = key;<br />      Data = data;<br />    }<br />    public int Key;<br />    public MyObject Data;<br />  }<br />  private LinkedList<Entry> DataList = new LinkedList<Entry>();<br />  private Dictionary<int,MyObject> DataDictionary = new Dictionary<int,MyObject>();<br />}
Note that I've omitted some things here, like the ability to enumerate the list.

 
Share this answer
 
Sure is, the framework gives you Dictionaries, which can do exactly what you need:

C#
<br />using System.Collections.Generic;<br />...<br />Dictionary<int,MyClass> MyDictionary = new Dictionary<int,MyClass>();<br />...<br />MyDictionary.Add(1,new MyClass(...));<br />MyDictionary.Add(2,new MyClass(...));<br />...<br />MyClass ClassNo1 = null;<br />if (MyDictionary.ContainsKey(1)) ClassNo1 = MyDictionary[1];<br />...<br />


Where "MyClass" is a custom structure you create to hold your multiple values.

 
Share this answer
 


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900