Counting the number of flags set on an enumeration

后端 未结 9 1563
孤街浪徒
孤街浪徒 2021-02-18 20:17

I\'m sure there must be a much better way of doing this. I\'m trying to do a count operation on a Flags enum. Before I was itterating over all the possible values and counting t

9条回答
  •  不要未来只要你来
    2021-02-18 21:04

    There's a straight-forward way using functional programming (LINQ):

    var skillCount = Enum
        .GetValues(typeof(Skills))
        .Cast()
        .Count(skills.HasFlag);
    

    It might be a bit slower than the bit-juggling solutions, but it's still allocation-free, has a constant run-time and is more intuitive.

提交回复
热议问题