开发者

.NET Enum type with multiple definitions

开发者 https://www.devze.com 2023-03-13 15:46 出处:网络
Imagine this enumerate: public enum eMyEnum { cValue1 = 0, cValue2 = 1, cValue2_too = 1开发者_开发问答,

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.


This should work:

var values = typeof(eMyEnum).GetEnumValues().Select(v => (int)v).Distinct();


This is the VB.NET Syntax if anybody is interested:

[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):

Enum.GetValues(typeof(eMyEnum)).Cast<eMyEnum>().Distinct

or

typeof(eMyEnum).GetEnumValues().Cast<eMyEnum>().Distinct


Linq could come to rescue for this:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消