简体   繁体   中英

C# List binary or items together into one bitmask result

I have a list of bit flags in c# in a list. I would like to binary or them together to generate a bitmask.

For example a modifierKey enum that is treated as a bit field with the Flags attribute like so:

[Flags]
public enum ModifierKeys : uint
{
    Alt = 1,
    Control = 2,
    Shift = 4,
    Win = 8
}

I know I can do this with a for loop and just bitwise or the values together as uints and then cast back to the enum type. My current working method looks like so:

public ModifierKeys ComputeMask(List<ModifierKeys> keys)
{
   uint value = 0;
   foreach(var item in keys)
   {
       value |= (uint)item;
   }

   return (ModifierKeys)value;
}

To my question - Can I do this be done with a single LINQ query or some other extension I am missing?

尝试这个:

uint value = keys.Aggregate<ModifierKeys, uint>(0, (current, item) => current | (uint)item);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM