标签云

微信群

扫码加入我们

WeChat QR Code

How can you enumerate an enum in C#?E.g. the following code does not compile:public enum Suit {Spades,Hearts,Clubs,Diamonds}public void EnumerateAllSuitsDemoMethod() {foreach (Suit suit in Suit) {DoSomething(suit);}}And gives the following compile-time error:'Suit' is a 'type' but is used like a 'variable'It fails on the Suit keyword, the second one.


See also ... stackoverflow.com/questions/972307/…

2019年06月25日23分18秒

You may want to check out the ins and outs of C# enums, which discusses this as well as other useful enum tidbits

2019年06月25日23分18秒

LOL had EXACTLY the same question (guess you want to do sth with poker?) :D

2019年06月25日23分18秒

This doesn't work if you have duplicate values in the enumerator list.

2019年06月26日23分18秒

I just want to point out that this, unfortunately won't work in silverlight, since the silverlight library don't comprise enum.GetValues. You have to use reflection in this case.

2019年06月26日23分18秒

Jessy this does work in case of duplicate situations like enum E {A = 0, B = 0}. Enum.GetValues results in two values being returned, though they are the same. E.A == E.B is true, so there is not distinction. If you want individual names, then you should look for Enum.GetNames.

2019年06月26日23分18秒

Then if you have duplicates/synonyms in your enum, and you want the other behavior, you can use Linq's Distinct extension (since .NET 3.5), so foreach (var suit in ((Suit[])Enum.GetValues(typeof(Suit))).Distinct()) { }.

2019年06月26日23分18秒

I made the mistake of trying to use var for the type. The compiler will make the variable an Object instead of the enum. List the enum type explicitly.

2019年06月25日23分18秒

VB Syntax here:link

2019年06月26日23分18秒

A one liner for the first extension method; it's no more lazy.return Enum.GetValues(typeof(T)).Cast<T>();

2019年06月26日23分18秒

Alternatively you could use OfType too: Enum.GetValues(typeof(T)).OfType<T>(). It's too bad there is not a generic version of GetValues<T>() then it would be even more slick.

2019年06月25日23分18秒

Maybe someone could show how to use these extensions? The compiler do not show extension methods on enum EnumExample.

2019年06月25日23分18秒

can anyone add example how to utilize those functions?

2019年06月25日23分18秒

+1 for reusable code: examples - save these extension methods in a library and reference it [Flags]public enum mytypes{name1, name2 }; List<string> myTypeNames = mytypes.GetAllItems();

2019年06月25日23分18秒

Why not use the yield keyword here instead instantiating a list?

2019年06月25日23分18秒

or shorter: return type.GetFields().Where(x => x.IsLiteral).Select(x => x.GetValue(null)).Cast<Enum>();

2019年06月26日23分18秒

nawfal: Linq isn't available .Net CF 2.0.

2019年06月25日23分18秒

Ekevoo How to bind this enum values to a DropDownList in MVC?

2019年06月26日23分18秒

This is pretty cool if you can use LINQ...

2019年06月26日23分18秒

This also works in the from clause and the foreach header declarator.

2019年06月26日23分18秒

Careful with using generics like this. If you try to use EnumLoop with some type that is not an enum, it will compile fine, but throw an exception at runtime.

2019年06月25日23分18秒

Thank you svick. Runtime exceptions will actually occur with the other answers on this page... except this one because I have added "where Key : struct, IConvertible" so that you get a compile time error in most cases.

2019年06月26日23分18秒

No, GetValues() is called only once in the foreach.

2019年06月25日23分18秒

James, I would discourage your class because clever is nice to write but in production code that many people will maintain and update, clever is extra work. If it makes a major saving or will be used a lot- so the savings is big and people will become familiar with it - it is worth it, but in most cases it slows down people trying to read and update the code and introduces a possible source bugs in the future. Less code is better :) less complexity is even better.

2019年06月25日23分18秒

GrantM Why? This code is neither complex, and it's incredibly short. On top of that, writing the class once will allow even shorter iterations of code with using is as per his example. This is extremely clean, if you can't update that code, you probably can't update any of the companies code.

2019年06月26日23分18秒

Nice solution, but some refactoring will be better! :)

2019年06月25日23分18秒

I am using .NET framework 4.0 & silverlight enum.getvalues work, the code I used is ---> enum.GetValues(typeof(enum))

2019年06月25日23分18秒

Starting with C# 7.3 (Visual Studio 2017 ≥ v15.7), one can use where T: Enum

2019年06月26日23分18秒

what about using T valueType = default(T)?

2019年06月26日23分18秒

Great, I didn't even know that keyword. Always nice to learn something new. Thank you! Does it always return a reference to the same object, or does it create a new instance each time the default statement is called? I haven't found anything on the net about this so far, but if it creates a new instance every time, it kind of defeats the purpose I was looking for (having a one-liner ^^).

2019年06月25日23分18秒

Wouldn't this create a new instance for every iteration over the enumeration?

2019年06月25日23分18秒

-1 for "supports type checking at compile time:". What type checking? This would work for any new() T. Also, you dont need new T() at all, you can select just the static fields alone and do .GetValue(null). See Aubrey's answer.

2019年06月25日23分18秒

Starting with C# 7.3 (Visual Studio 2017 ≥ v15.7), one can use where T: Enum

2019年06月26日23分18秒

Enum.GetValues(Suits)

2019年06月25日23分18秒

That enumerates a string, don't forget to convert those things back to an enumeration value so the enumeration can be enumerated.

2019年06月26日23分18秒

I see from your edit that you want to actually operate on the enums themselves, the above code addressed your original post.

2019年06月25日23分18秒

The compiler should take care of this, though.

2019年06月25日23分18秒

StephanBijzitter Wow, you're reading pretty far down on this one :-) I agree, the compiler should make my solution unnecessary.

2019年06月26日23分18秒

This is not necessary.Looking at the compiled code in ILSpy, the compiler definitely already does this.Why is this answer upvoted at all, much less 35 times?

2019年06月26日23分18秒

It was upvoted a long time ago. A very long time ago. I would wager that the compiler would have solved this back then, too, though. But it sure looks more performant, doesn't it? ;-)

2019年06月26日23分18秒

This is a nice summary of methods. I think you should merge your other answer into this though. The truth is that enum are special and looping through them is often (usually) just as valid as enumeration because you know that the values will never change. IOW, If you have an enum that is changing all the time then you've chosen the wrong data construct to begin with.

2019年06月26日23分18秒

Starting with C# 7.3 (Visual Studio 2017 ≥ v15.7), one can use where T: Enum

2019年06月26日23分18秒

Who is down voting....it works perfectly... and at least add a comment what they think is wrong?

2019年06月25日23分18秒

downvoting without even giving the reason is really not fair

2019年06月26日23分18秒

Maybe 'cos this is already covered in many answers? Let's not make answers redundant.

2019年06月25日23分18秒

nawfal yes may be covered in other answers, though not concluded well in most of them.

2019年06月25日23分18秒

Starting with C# 7.3 (Visual Studio 2017 ≥ v15.7), one can use where T: Enum

2019年06月26日23分18秒

will this work if the values in enum are not sequential?

2019年06月25日23分18秒

Is that lisp?

2019年06月26日23分18秒

A Dictionary is not a good idea: if you have an Enum like enum E { A = 0, B = 0 }, the 0 value is added 2 times generating an ArgumentException (you cannot add the same Key on a Dictionary 2 or more times!).

2019年06月25日23分18秒

Why return a Dictionary<,> from a method named ToList? Also why not return Dictionary<T, string>?

2019年06月25日23分18秒

Although your answer is correct in itself, it doesn't really address the OP's original question. The GetNames method returns, indeed, a string array, but the OP requires an enumerator through the values.

2019年06月25日23分18秒

SilviuPreda: Edited. It should have been GetValues instead of GetNames.

2019年06月26日23分18秒

This has already been mentioned in many answers above. Please check the answers before posting.

2019年06月26日23分18秒