Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Converting set flags in a variable of type flag enumeration to an array of integers

I came up with this piece of code that converts the set flags in a variable of type Flag Enumeration and returns the set flags as integers. I'd like to know if this is the best approach.

Example enumeration:

[Flags]
enum Status {
  None = 0x0,
  Active = 0x1,
  Inactive = 0x2,
  Canceled = 0x4,
  Suspended = 0x8
}

The extension method that converts the set flags to array of int that I came up with:

public static class Extensions
{
    public static int[] ToIntArray(this System.Enum o) 
    {
        return o.ToString()
            .Split(new string[] { ", " }, StringSplitOptions.None)
            .Select(i => (int)Enum.Parse(o.GetType(), i))
            .ToArray();
    }
}

This is how I use it:

Status filterStatus = Status.Suspended | Status.Canceled;

int[] filterFlags = filterStatus.toIntArray();

foreach (int flag in filterFlags) {
   Console.WriteLine("{0}\n", flag);
}

It will output:

4
8

As you can see, to get this done I'm doing the following:

  1. Converting the variable to string. It outputs something like: Suspended, Canceled
  2. Splitting that string into an array of strings: { "Suspended", "Canceled" }
  3. Converting that string to the enumeration value with Enum.Parse.
  4. Casting the value to an integer.
  5. Converting the IEnumerable to int[].

It works, but I just don't think it's the best approach. Any suggestions to improve this bit of code?

like image 575
Cameri Avatar asked Jul 08 '10 21:07

Cameri


People also ask

Bahasa C digunakan untuk apa?

Meskipun C dibuat untuk memprogram sistem dan jaringan komputer namun bahasa ini juga sering digunakan dalam mengembangkan software aplikasi. C juga banyak dipakai oleh berbagai jenis platform sistem operasi dan arsitektur komputer, bahkan terdapat beberepa compiler yang sangat populer telah tersedia.

C dalam Latin berapa?

C adalah huruf ketiga dalam alfabet Latin. Dalam bahasa Indonesia, huruf ini disebut ce (dibaca [tʃe]).

Bahasa C dibuat pertama kali oleh siapa dan tahun berapa?

Bahasa pemrograman C ini dikembangkan antara tahun 1969 – 1972 oleh Dennis Ritchie. Yang kemudian dipakai untuk menulis ulang sistem operasi UNIX. Selain untuk mengembangkan UNIX, bahasa C juga dirilis sebagai bahasa pemrograman umum.


1 Answers

To keep it linq-like

var flags = Enum.GetValues(typeof(Status))
                .Cast<int>()
                .Where(f=> f & o == f)
                .ToList();

One gotcha with this approach is that it will include aggregate enumeration values. For example:

[Flags]
public enum Status
{
    None = 0,
    One = 1,
    Two = 2,
    All = One | Two,
}

var flags = Enum.GetValues(typeof(Status))
                .Cast<int>()
                .Where(f=> f & o == f)
                .ToList();

Here flags will have 1, 2, 3, not just 1, 2.

like image 91
Steve Mitcham Avatar answered Oct 17 '22 03:10

Steve Mitcham