Imagine this enumerate:
想象一下这个枚举:
public enum eMyEnum
{
cValue1 = 0,
cValue2 = 1,
cValue2_too = 1,
cValue3 = 5
}
Is there a way to iterate over all the values (not the labels)? If I try
有没有办法迭代所有的值(而不是标签)?如果我试试
var values = typeof(eMyEnum).GetEnumValues();
I end up with {cValue1,cValue2,cValue2,cValue3}
, while I'm looking for a way to retrieve {cValue1,cValue2,cValue3}
. Note: I intentionally left a gap between 1 and 5.
我最终得到{cValue1,cValue2,cValue2,cValue3},而我正在寻找一种方法来检索{cValue1,cValue2,cValue3}。注意:我故意留下1到5之间的差距。
3 个解决方案
#1
2
This is the VB.NET Syntax if anybody is interested:
这是VB.NET语法,如果有人感兴趣:
[Enum].GetValues(GetType(eMyEnum)).Cast(of eMyEnum).Distinct
or
要么
GetType(eMyEnum).GetEnumValues().Cast(of eMyEnum).Distinct
so this should be the C# version (cannot test):
所以这应该是C#版本(无法测试):
Enum.GetValues(typeof(eMyEnum)).Cast<eMyEnum>().Distinct
or
要么
typeof(eMyEnum).GetEnumValues().Cast<eMyEnum>().Distinct
#2
3
This should work:
这应该工作:
var values = typeof(eMyEnum).GetEnumValues().Select(v => (int)v).Distinct();
#3
0
Linq could come to rescue for this:
Linq可以为此解救:
IEnumerable<eMyEnum> values = typeof(eMyEnum).GetEnumValues()
.Cast<int>().Distinct().Cast<eMyEnum>();
Note that this will get you only cValue2 and not cValue2_too i think.
请注意,我认为这只会让你获得cValue2而不是cValue2_too。
#1
2
This is the VB.NET Syntax if anybody is interested:
这是VB.NET语法,如果有人感兴趣:
[Enum].GetValues(GetType(eMyEnum)).Cast(of eMyEnum).Distinct
or
要么
GetType(eMyEnum).GetEnumValues().Cast(of eMyEnum).Distinct
so this should be the C# version (cannot test):
所以这应该是C#版本(无法测试):
Enum.GetValues(typeof(eMyEnum)).Cast<eMyEnum>().Distinct
or
要么
typeof(eMyEnum).GetEnumValues().Cast<eMyEnum>().Distinct
#2
3
This should work:
这应该工作:
var values = typeof(eMyEnum).GetEnumValues().Select(v => (int)v).Distinct();
#3
0
Linq could come to rescue for this:
Linq可以为此解救:
IEnumerable<eMyEnum> values = typeof(eMyEnum).GetEnumValues()
.Cast<int>().Distinct().Cast<eMyEnum>();
Note that this will get you only cValue2 and not cValue2_too i think.
请注意,我认为这只会让你获得cValue2而不是cValue2_too。