Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building a bit flag using linq / lambda

Is it possible to build up a bit mask based on the result of a linq query; for example:

class MyClass
{
    public int Flag{get;set;}
    public bool IsSelected {get;set;}
}

myVar = GetlistMyClass();

int myFlag = myVar.Where(a => a.IsSelected).Select(?);
like image 806
Paul Michaels Avatar asked Dec 12 '14 11:12

Paul Michaels


2 Answers

You can aggregate all flags by using the |-operator like this:

int myFlag = myVar.Where(a => a.IsSelected)
                  .Select(x => x.Flag) 
                  .Aggregate((current, next) => current | next);
like image 92
nvoigt Avatar answered Oct 20 '22 19:10

nvoigt


Do you mean a bit flag as in a power of two?

Like this:

Func<int, int> pow2 = null;
pow2 = n => n == 0 ? 1 : 2 * pow2(n - 1);

int myFlag = myVar.Reverse().Select((a, n) => a.IsSelected ? pow2(n) : 0).Sum();

Or do yo simply mean this:

int myFlag = myVar.Where(a => a.IsSelected).Any();
like image 26
Enigmativity Avatar answered Oct 20 '22 19:10

Enigmativity