Insert Int array in Enum Flags

I have the following flags enumeration:

[Flags] public enum DataFiat { Public = 1, Listed = 2, Client = 4 } // DataFiat 

And I have an int array, for example:

 int[] selected = new int[] { 1, 4 } 

How can I convert this to my listing, which will become:

 DataFiat.Public | DataFiat.Client 

Thanks Miguel

+7
c #
source share
6 answers

How about something like

 var tt = (DataFiat)selected.Aggregate((i, t) => i | t); 
+3
source share
 var f = (DataFiat)selected.Sum(); 
+6
source share

this snippet:

  var intArr = new[] { 1, 4 }; var sum = intArr.Sum(x => x); var result = (Test)sum; 

returns

enter image description here

+3
source share
 DataFlat result = (DataFlat) 0; foreach (var value in selected) { result |= (DataFlat)value; } 

Or if you want to use LINQ

 DataFlat result = (DataFlat) selected.Aggregate(0, (old, current) => old | current); 
+2
source share

Do you mean this?

 IEnumerable<DataFiat> selectedDataFiats = selected.Cast<DataFiat>(); 

This sinmply drops every int up to DataFiat .

+1
source share

You cannot just pass an array if it is really an object []. You can easily create a new array:

 var enumArray = originalArray.Cast<DataFiat>().ToArray(); 

If it was actually an int [] array, you can use it - although you would need to talk well with the C # compiler:

 using System; class Program { enum Foo { Bar = 1, Baz = 2 } static void Main() { int[] ints = new int[] { 1, 2 }; Foo[] foos = (Foo[]) (object) ints; foreach (var foo in foos) { Console.WriteLine(foo); } } } 

The C # compiler does not consider that there is a conversion from int [] to Foo [] (and there isn’t in C # rules) ... but the CLR is ok with this conversion, so since you can convince the C # compiler to play (the first time you click on an object).

This does not work when the original array is really an object [].

Hope this helps.

+1
source share

All Articles