Search code examples
c#shorthand

Integer array to int as map of set bits (one line shorthand)


I need a map of positive values.

And looking for one-line equivalent of following example:

int[] workplace = new int[]{1, 3, 5, 0, 7, 0, 9, 0, 3, 2, 0, 4};
int map = 0;
for (int i = 0; i < workplace.Length; i++)
    map |= workplace[i] > 0 ? 1 << i : 0;

like:

int[] workplace = new int[]{1, 3, 5, 0, 7, 0, 9, 0, 3, 2, 0, 4};
int map = bla bla bla...;

Solution

  • Int32 map = workplace.Select( ( n, idx ) => ( n > 0 ) ? ( 1 << idx ) : 0 ).Aggregate( seed: 0, func: ( agg, n ) => agg | n );
    

    Works for me:

    enter image description here