[英]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>
)? [C#] 嗨,对于由枚举表示的两个值(即类似
Dict<int, enum, enum>
)的 int 键匹配查找或 dict 之类的东西的最佳解决方案是什么? I need to take those two enums and find the assosiated int number for them.我需要获取这两个枚举并为它们找到相关的 int 数。 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
我也发现了类似 Lookup 结构的东西,但我仍然不知道什么是最好的方法,因为我是一个新手
If your enum is an int you can just cast as such如果你的枚举是一个 int 你可以这样转换
int enumNumber = (int) exampleenum.keyA;
so enumNumber would be cast as 1 for the below.所以 enumNumber 将被强制转换为 1 以下。
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.然后您可以使用 linq 查找值并键入键。
int Key = dic.FirstOrDefault(x => x.Value == new EnumObject() { Enum1 = exampleenum.KeyA, Enum2 = exampleenum.KeyB }).Key;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.