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:
It works, but I just don't think it's the best approach. Any suggestions to improve this bit of code?
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 adalah huruf ketiga dalam alfabet Latin. Dalam bahasa Indonesia, huruf ini disebut ce (dibaca [tʃe]).
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With