简体   繁体   中英

LookUp for two enum values

[C#] Hi, What is the best solution to have something like a lookup or dict that would match an int key for two values represented by enums (ie something like Dict<int, enum, enum> )? I need to take those two enums and find the assosiated int number for them. I am looking for the best approach. I found that maybe creation of new object would be to represent those two enums or use a Tuple there. I also found osmething like Lookup structure, but I still don't know what would be the best approach, cause I am a freshie

If your enum is an int you can just cast as such

int enumNumber = (int) exampleenum.keyA;

so enumNumber would be cast as 1 for the below.

private enum exampleenum
{
    KeyA = 1,
    KeyB = 2,
    KeyC = 3,
    KeyD = 4
}

A dictionary can't have two values, it is a is key value pair (two). To use a dictionary with two values you will need to make a custom object for your two enums as.

I am not sure what over heads this would have performance wise you may want to look into using a Tuple instead.

Example object

class EnumObject
{
    public Enum Enum1 { get; set; }
    public Enum Enum2 { get; set; }
}

Populating the dictionary

        Dictionary<int, EnumObject> dic = new Dictionary<int, EnumObject>()
        {
            {1, new EnumObject() { Enum1 = exampleenum.KeyA, Enum2 = exampleenum.KeyB }},
            {2, new EnumObject() { Enum1 = exampleenum.KeyA, Enum2 = exampleenum.KeyC }},
            {3, new EnumObject() { Enum1 = exampleenum.KeyA, Enum2 = exampleenum.KeyD }}
        };

Then you can use linq to lookup the value and key the key.

        int Key = dic.FirstOrDefault(x => x.Value == new EnumObject() { Enum1 = exampleenum.KeyA, Enum2 = exampleenum.KeyB }).Key;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM