Creating a bit flag using linq / lambda

Is it possible to create a bitmask based on the result of a linq query? eg:

class MyClass { public int Flag{get;set;} public bool IsSelected {get;set;} } myVar = GetlistMyClass(); int myFlag = myVar.Where(a => a.IsSelected).Select(?); 
+5
source share
2 answers

You can aggregate all flags with | -operator as follows:

 int myFlag = myVar.Where(a => a.IsSelected) .Select(x => x.Flag) .Aggregate((current, next) => current | next); 
+5
source

You mean a bit flag, as in the 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 simply means this:

 int myFlag = myVar.Where(a => a.IsSelected).Any(); 
+1
source

Source: https://habr.com/ru/post/1208879/


All Articles