C# Dictionary with two Values per Key?

前端 未结 10 1301
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 17:36

I have a situation in code where a Dictionary seemed like the best idea - I need a collection of these objects and I need them to be acces

相关标签:
10条回答
  • 2020-12-13 17:49

    A Dictionary is just a keyed collection of objects. As such, it will hold any type of object you want. Even the simplest of objects, like, say, an array (which derives from Object), but requires a lot less code on your behalf.

    Rather than writing an entire class, stuff a dynamically allocated array, or a List in the value and run with that.

    Dictionaries are highly flexible that way.

    0 讨论(0)
  • 2020-12-13 17:51

    I think generally you're getting into the concept of Tuples - something like Tuple<x, y, z>, or Tuple<string, bool, value>.

    C# 4.0 will have dynamic support for tuples, but other than that, you need to roll your own or download a Tuple library.

    You can see my answer here where I put some sample code for a generic tuple class. Or I can just repost it here:

    public class Tuple<T, T2, T3>
    {
        public Tuple(T first, T2 second, T3 third)
    
        {
            First = first;
            Second = second;
            Third = third;
        }
    
        public T First { get; set; }
        public T2 Second { get; set; }
        public T3 Third { get; set; }
    
    }
    
    0 讨论(0)
  • 2020-12-13 17:52
    class MappedValue
    {
        public string SomeString { get; set; }
        public bool SomeBool { get; set; }
    }
    
    Dictionary<string, MappedValue> myList = new Dictionary<string, MappedValue>;
    
    0 讨论(0)
  • 2020-12-13 17:52

    I don't believe .net has Multi-Map built in which is generally a data-structure you can use to do this type of storage. On the other hand I don't think it's overkill at all just using a custom object that holds both a string and a boolean.

    0 讨论(0)
  • 2020-12-13 17:53

    What about Lookup class?

    Edit:

    After read the question carefully think this is not the best solution, but it still a good one for the dictionary with some values per a single key.

    0 讨论(0)
  • 2020-12-13 18:01

    Actually, what you've just described is an ideal use for the Dictionary collection. It's supposed to contain key:value pairs, regardless of the type of value. By making the value its own class, you'll be able to extend it easily in the future, should the need arise.

    0 讨论(0)
提交回复
热议问题