Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从字典中的值中获取关键字_C# - Fatal编程技术网

C# 如何从字典中的值中获取关键字

C# 如何从字典中的值中获取关键字,c#,C#,我定义了Enum和Dictionary,如下所示。 现在在字典中,我想使用Linq从值中获取键 enum Devices { Fan, Bulb, Mobile, Television }; Dictionary<int, Devices> dctDevices = new Dictionary<int, Devices>() { {1, Devices.Fan}, {2,

我定义了
Enum
Dictionary
,如下所示。 现在在
字典
中,我想使用
Linq
中获取

enum Devices
    {
        Fan,
        Bulb,
        Mobile,
        Television
    };

Dictionary<int, Devices> dctDevices = new Dictionary<int, Devices>()
{
    {1, Devices.Fan},
    {2, Devices.Bulb},
    {3, Devices.Mobile},
    {4, Devices.Television}
};

请向我建议执行此操作的最佳方式。提前感谢

您可以按以下方式操作:

dctDevices.AsEnumerable().Where(p => p.Value == Devices.Bulb).FirstOrDefault().Key;

该方法可以如下所示:

int GetKeyFromValue(Devices device)
{
    return dctDevices.Keys
        .Where(k => dctDevices[k] == device)
        .DefaultIfEmpty( -1 ) // or whatever "not found"-value
        .First();
}
或任何类型的通用扩展方法:

public static TKey GetKeyByBalue<TKey, TValue>(this IDictionary<TKey, TValue> dict, TValue value, TKey notFoundKey, IEqualityComparer<TValue> comparer = null)
{
    if (comparer == null)
        comparer = EqualityComparer<TValue>.Default;
    return dict.Keys.Where(k => comparer.Equals(dict[k], value)).DefaultIfEmpty(notFoundKey).First();
}

或者创建一个自定义类
Device
,该类封装了ID和
Devices
(以及其他内容):

对不起,它的计数器1、2、3、4可能是一个问题,为什么不改为
Dictionary
:PI要说的和@VladiPavelka一样,为什么不使用设备作为键呢?顺便说一句。如果你不另外指定,
enum
值基本上已经是
int
值(从
0
开始)。我不知道键实际应该表示什么,但您的用例可能只是:
intkey=(int)value+1但这是实际需求。我一开始不会放字典。谢谢您的建议。当我尝试搜索字典中未添加的值时,它会出错。我编辑了我的答案,您能再试一次吗?如果键不存在,它总是返回0。但是键值0可以存在。然后您可以检查dctDevices.ContainsValue(Devices.tv)如果未添加它,您可以返回您需要的内容。只需通过
var backwards=dctDevices.ToDictionary创建“backwards”字典(x=>x.value,x=>x.key)ToLookup
。@Corak:关键是他不需要总是创建它,这就是为什么我没有显示创建过程,而是手动初始化了一次字典。是的,你们也可以用这种方式初始化它。谢谢,第一个答案帮助了我。如果不存在,则返回-1。
public static TKey GetKeyByBalue<TKey, TValue>(this IDictionary<TKey, TValue> dict, TValue value, TKey notFoundKey, IEqualityComparer<TValue> comparer = null)
{
    if (comparer == null)
        comparer = EqualityComparer<TValue>.Default;
    return dict.Keys.Where(k => comparer.Equals(dict[k], value)).DefaultIfEmpty(notFoundKey).First();
}
Dictionary<Devices, int> DeviceKeys = new Dictionary<Devices, int>()
{
    {Devices.Fan, 1}, // ...
};
int key = DeviceKeys[Devices.Bulb];