Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Enumerate through the values of a enum

Enumerate through the values of a enum

Scheduled Pinned Locked Moved C#
csharpquestionlounge
11 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    Sentenryu
    wrote on last edited by
    #1

    ok, I Know about Enum.GetValues(), but what i want to know if is possible is to do a foreach through the values of a enum such as i can do the following:

    foreach(var value in enum){
    list.Add(new SelectListItem(){
    Text = value.ToString(),
    Value = ((int)value).ToString()
    });
    }

    say that i have the following enum:

    enum States{
    Running,
    Stoped,
    Paused
    }

    the only way to accomplish what i described above is through the use of Enum.GetValues() and Enum.GetNames()? or there is some syntax sugar? I'm asking more out of curiosity than anything else ;)

    I'm brazilian and english (well, human languages in general) aren't my best skill, so, sorry by my english. (if you want we can speak in C# or VB.Net =p)

    D J 2 Replies Last reply
    0
    • S Sentenryu

      ok, I Know about Enum.GetValues(), but what i want to know if is possible is to do a foreach through the values of a enum such as i can do the following:

      foreach(var value in enum){
      list.Add(new SelectListItem(){
      Text = value.ToString(),
      Value = ((int)value).ToString()
      });
      }

      say that i have the following enum:

      enum States{
      Running,
      Stoped,
      Paused
      }

      the only way to accomplish what i described above is through the use of Enum.GetValues() and Enum.GetNames()? or there is some syntax sugar? I'm asking more out of curiosity than anything else ;)

      I'm brazilian and english (well, human languages in general) aren't my best skill, so, sorry by my english. (if you want we can speak in C# or VB.Net =p)

      D Offline
      D Offline
      Dave Kreskowiak
      wrote on last edited by
      #2

      Nope. No syntactic sugar. Since an Enum is not enumerable, you can't just specify the enum type itself. You must get the enum values in an array or other IEnumerable implementor first.

      A guide to posting questions on CodeProject[^]
      Dave Kreskowiak

      S 1 Reply Last reply
      0
      • D Dave Kreskowiak

        Nope. No syntactic sugar. Since an Enum is not enumerable, you can't just specify the enum type itself. You must get the enum values in an array or other IEnumerable implementor first.

        A guide to posting questions on CodeProject[^]
        Dave Kreskowiak

        S Offline
        S Offline
        Sentenryu
        wrote on last edited by
        #3

        and the only way to do this and maintain the type of the enum is adding the values manually to the list... I was thinking of someway to call a method with every possibly constant of a enum, but the only thing i got so far is something like:

        foreach(int value in Enum.GetValues(typeof(MyEnum))){
            MyEnum e = (MyEnum)value;
            ...
        }
        

        or if you prefer the linq way...

        ((IEnumerable)Enum.GetValues(typeof(MyEnum))).Select(x => (MyEnum)x);

        the only thing i don't understand is why i can't call the Select method directly on the return of Enum.GetValues(), maybe because Array implements the non-generic IEnumerable interface?

        I'm brazilian and english (well, human languages in general) aren't my best skill, so, sorry by my english. (if you want we can speak in C# or VB.Net =p)

        D 1 Reply Last reply
        0
        • S Sentenryu

          and the only way to do this and maintain the type of the enum is adding the values manually to the list... I was thinking of someway to call a method with every possibly constant of a enum, but the only thing i got so far is something like:

          foreach(int value in Enum.GetValues(typeof(MyEnum))){
              MyEnum e = (MyEnum)value;
              ...
          }
          

          or if you prefer the linq way...

          ((IEnumerable)Enum.GetValues(typeof(MyEnum))).Select(x => (MyEnum)x);

          the only thing i don't understand is why i can't call the Select method directly on the return of Enum.GetValues(), maybe because Array implements the non-generic IEnumerable interface?

          I'm brazilian and english (well, human languages in general) aren't my best skill, so, sorry by my english. (if you want we can speak in C# or VB.Net =p)

          D Offline
          D Offline
          Dave Kreskowiak
          wrote on last edited by
          #4

          Sentenryu wrote:

          the only thing i don't understand is why i can't call the Select method directly on the return of Enum.GetValues(), maybe because Array implements the non-generic IEnumerable interface?

          LINQ works on the IQueryable interface, which array's don't support. Arrays support the following interfaces: ICloneable, IList, ICollection, IEnumerable, IStructuralComparable and IStructuralEquatable The .Select extension works on any IEnumerable, including arrays, so I think your .Select example is a bit flawed. I don't know what you're doing, but...

          A guide to posting questions on CodeProject[^]
          Dave Kreskowiak

          S J 2 Replies Last reply
          0
          • D Dave Kreskowiak

            Sentenryu wrote:

            the only thing i don't understand is why i can't call the Select method directly on the return of Enum.GetValues(), maybe because Array implements the non-generic IEnumerable interface?

            LINQ works on the IQueryable interface, which array's don't support. Arrays support the following interfaces: ICloneable, IList, ICollection, IEnumerable, IStructuralComparable and IStructuralEquatable The .Select extension works on any IEnumerable, including arrays, so I think your .Select example is a bit flawed. I don't know what you're doing, but...

            A guide to posting questions on CodeProject[^]
            Dave Kreskowiak

            S Offline
            S Offline
            Sentenryu
            wrote on last edited by
            #5

            First of all, i forgot to say thanks for your answer, so Thanks! In the case i'm just getting a IEnumerable<SelectListItem> with the values of a enum to display as radiobuttons, the actual code (with the excuse of having names in portuguese) is this:

            ViewBag.ApetiteOptions = ((IEnumerable)Enum.GetValues(typeof(Apetite))).Select(x => new SelectListItem() {
            Text = ((Apetite)x).ToString(),
            Value = x.ToString()
            });

            Visual Studio (2012) gives me an error when I try to use the select method directly on the return type of the Enum.GetValues(), I guess it's because this method returns a instace of Array(the base class), and not a instance of int[]. int[] implements IEnumerable<int>, while Array implements IEnumerable, the Select method Expects IEnumerable<TSource>... while writting this post, i updated this bit of code to this:

            ViewBag.ApetiteOptions = Enum.GetValues(typeof(Apetite)).OfType().Select(x => new SelectListItem() {
            Text = ((Apetite)x).ToString(),
            Value = x.ToString()
            });

            I'm a little bit more happy now :)

            I'm brazilian and english (well, human languages in general) aren't my best skill, so, sorry by my english. (if you want we can speak in C# or VB.Net =p)

            L J 2 Replies Last reply
            0
            • S Sentenryu

              First of all, i forgot to say thanks for your answer, so Thanks! In the case i'm just getting a IEnumerable<SelectListItem> with the values of a enum to display as radiobuttons, the actual code (with the excuse of having names in portuguese) is this:

              ViewBag.ApetiteOptions = ((IEnumerable)Enum.GetValues(typeof(Apetite))).Select(x => new SelectListItem() {
              Text = ((Apetite)x).ToString(),
              Value = x.ToString()
              });

              Visual Studio (2012) gives me an error when I try to use the select method directly on the return type of the Enum.GetValues(), I guess it's because this method returns a instace of Array(the base class), and not a instance of int[]. int[] implements IEnumerable<int>, while Array implements IEnumerable, the Select method Expects IEnumerable<TSource>... while writting this post, i updated this bit of code to this:

              ViewBag.ApetiteOptions = Enum.GetValues(typeof(Apetite)).OfType().Select(x => new SelectListItem() {
              Text = ((Apetite)x).ToString(),
              Value = x.ToString()
              });

              I'm a little bit more happy now :)

              I'm brazilian and english (well, human languages in general) aren't my best skill, so, sorry by my english. (if you want we can speak in C# or VB.Net =p)

              L Offline
              L Offline
              Lost User
              wrote on last edited by
              #6

              Nice one,

              1 Reply Last reply
              0
              • S Sentenryu

                ok, I Know about Enum.GetValues(), but what i want to know if is possible is to do a foreach through the values of a enum such as i can do the following:

                foreach(var value in enum){
                list.Add(new SelectListItem(){
                Text = value.ToString(),
                Value = ((int)value).ToString()
                });
                }

                say that i have the following enum:

                enum States{
                Running,
                Stoped,
                Paused
                }

                the only way to accomplish what i described above is through the use of Enum.GetValues() and Enum.GetNames()? or there is some syntax sugar? I'm asking more out of curiosity than anything else ;)

                I'm brazilian and english (well, human languages in general) aren't my best skill, so, sorry by my english. (if you want we can speak in C# or VB.Net =p)

                J Offline
                J Offline
                J4amieC
                wrote on last edited by
                #7

                GetValues() does return an enumerable list of the actual enums, so your original code works with VERY few changes:

                foreach(var value in Enum.GetValues(typeof(States))){
                list.Add(new SelectListItem(){
                Text = value.ToString(),
                Value = ((int)value).ToString()
                });
                }

                Live example: http://rextester.com/PWOX45762[^] You can also use LINQ if you want, but that call to Enum.GetValues() returns an Array, so you neeed to call OfType() to coerce it to a generic IEnumerable

                var list = Enum.GetValues(typeof(States))
                .OfType()
                .Select(i => .... );

                Live example: http://rextester.com/TRHMMB31708[^]

                S 1 Reply Last reply
                0
                • D Dave Kreskowiak

                  Sentenryu wrote:

                  the only thing i don't understand is why i can't call the Select method directly on the return of Enum.GetValues(), maybe because Array implements the non-generic IEnumerable interface?

                  LINQ works on the IQueryable interface, which array's don't support. Arrays support the following interfaces: ICloneable, IList, ICollection, IEnumerable, IStructuralComparable and IStructuralEquatable The .Select extension works on any IEnumerable, including arrays, so I think your .Select example is a bit flawed. I don't know what you're doing, but...

                  A guide to posting questions on CodeProject[^]
                  Dave Kreskowiak

                  J Offline
                  J Offline
                  J4amieC
                  wrote on last edited by
                  #8

                  Dave Kreskowiak wrote:

                  LINQ works on the IQueryable interface, which array's don't support.

                  No, LINQ to SQL / EF works on IQueryable, most of Linq2Objects works on IEnumerable

                  D 1 Reply Last reply
                  0
                  • S Sentenryu

                    First of all, i forgot to say thanks for your answer, so Thanks! In the case i'm just getting a IEnumerable<SelectListItem> with the values of a enum to display as radiobuttons, the actual code (with the excuse of having names in portuguese) is this:

                    ViewBag.ApetiteOptions = ((IEnumerable)Enum.GetValues(typeof(Apetite))).Select(x => new SelectListItem() {
                    Text = ((Apetite)x).ToString(),
                    Value = x.ToString()
                    });

                    Visual Studio (2012) gives me an error when I try to use the select method directly on the return type of the Enum.GetValues(), I guess it's because this method returns a instace of Array(the base class), and not a instance of int[]. int[] implements IEnumerable<int>, while Array implements IEnumerable, the Select method Expects IEnumerable<TSource>... while writting this post, i updated this bit of code to this:

                    ViewBag.ApetiteOptions = Enum.GetValues(typeof(Apetite)).OfType().Select(x => new SelectListItem() {
                    Text = ((Apetite)x).ToString(),
                    Value = x.ToString()
                    });

                    I'm a little bit more happy now :)

                    I'm brazilian and english (well, human languages in general) aren't my best skill, so, sorry by my english. (if you want we can speak in C# or VB.Net =p)

                    J Offline
                    J Offline
                    J4amieC
                    wrote on last edited by
                    #9

                    See my answer below, all your LINQ example is missing is a call to

                    OfType()

                    1 Reply Last reply
                    0
                    • J J4amieC

                      Dave Kreskowiak wrote:

                      LINQ works on the IQueryable interface, which array's don't support.

                      No, LINQ to SQL / EF works on IQueryable, most of Linq2Objects works on IEnumerable

                      D Offline
                      D Offline
                      Dave Kreskowiak
                      wrote on last edited by
                      #10

                      Crap. That's what I get with 4 hours of sleep... :-\

                      A guide to posting questions on CodeProject[^]
                      Dave Kreskowiak

                      1 Reply Last reply
                      0
                      • J J4amieC

                        GetValues() does return an enumerable list of the actual enums, so your original code works with VERY few changes:

                        foreach(var value in Enum.GetValues(typeof(States))){
                        list.Add(new SelectListItem(){
                        Text = value.ToString(),
                        Value = ((int)value).ToString()
                        });
                        }

                        Live example: http://rextester.com/PWOX45762[^] You can also use LINQ if you want, but that call to Enum.GetValues() returns an Array, so you neeed to call OfType() to coerce it to a generic IEnumerable

                        var list = Enum.GetValues(typeof(States))
                        .OfType()
                        .Select(i => .... );

                        Live example: http://rextester.com/TRHMMB31708[^]

                        S Offline
                        S Offline
                        Sentenryu
                        wrote on last edited by
                        #11

                        Wow, I always thought it returned a Array containing int's, this will really simplify the things! thanks a lot! :-D

                        I'm brazilian and english (well, human languages in general) aren't my best skill, so, sorry by my english. (if you want we can speak in C# or VB.Net =p)

                        1 Reply Last reply
                        0
                        Reply
                        • Reply as topic
                        Log in to reply
                        • Oldest to Newest
                        • Newest to Oldest
                        • Most Votes


                        • Login

                        • Don't have an account? Register

                        • Login or register to search.
                        • First post
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • World
                        • Users
                        • Groups