努力寻找合适的数据结构 [英] Struggling to find a suitable data structure

查看:87
本文介绍了努力寻找合适的数据结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,

我正在寻找一个C#数据结构,该结构将允许我使用相同的键存储多个值,然后再浏览该数据结构并提取最新的条目.给定密钥.

我打算将int值用作键,并将自定义对象用作值.

感谢

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

推荐答案

如果您需要保留所有值,但仍然能够检索一个值的最新值给定键,您可以使用ListLinkedList存储所有值,并使用Dictionary保存给定键的值,如下所示:
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.


当然,该框架为您提供了Dictionary,它们可以完全满足您的需要:

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

<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 />



其中"MyClass"是自定义结构您创建以保存多个值.



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


这篇关于努力寻找合适的数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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