c# - .NET Flag Enum get Attributes from values -
greetings stackoverflow,
if i've got enum type flag attribute values in enum type own attributes, how can retrieve of appropriate attributes?
for example:
[flags()] enum myenum { [enumdisplayname("enum value 1")] enumvalue1 = 1, [enumdisplayname("enum value 2")] enumvalue2 = 2, [enumdisplayname("enum value 3")] enumvalue3 = 4, } void foo() { var enumvar = myenum.enumvalue2 | myenum.enumvalue3; // collection of enumdisplayname attribute objects enumvar ... }
a quick , dirty way using linq:
ienumerable<enumdisplaynameattribute> attributes = enum.getvalues(typeof(myenum)) .cast<myenum>() .where(v => enumvar.hasflag(v)) .select(v => typeof(myenum).getfield(v.tostring())) .select(f => f.getcustomattributes(typeof(enumdisplaynameattribute), false)[0]) .cast<enumdisplaynameattribute>();
or in query syntax:
ienumerable<enumdisplaynameattribute> attributes = myenum v in enum.getvalues(typeof(myenum)) enumvar.hasflag(v) let f = typeof(myenum).getfield(v.tostring()) let = f.getcustomattributes(typeof(enumdisplaynameattribute), false)[0] select ((enumdisplaynameattribute)a);
alternatively, if there possibly multiple attributes on each field, you'll want this:
ienumerable<enumdisplaynameattribute> attributes = enum.getvalues(typeof(myenum)) .cast<myenum>() .where(v => enumvar.hasflag(v)) .select(v => typeof(myenum).getfield(v.tostring())) .selectmany(f => f.getcustomattributes(typeof(enumdisplaynameattribute), false)) .cast<enumdisplaynameattribute>();
or in query syntax:
ienumerable<enumdisplaynameattribute> attributes = myenum v in enum.getvalues(typeof(myenum)) enumvar.hasflag(v)) let f = typeof(myenum).getfield(v.tostring()) enumdisplaynameattribute in f.getcustomattributes(typeof(enumdisplaynameattribute), false) select a;
Comments
Post a Comment