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)在这种情况下,因为OP似乎期望严格的1:1关系。否则,可能需要一个类似的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];