Counting the number of flags set on an enumeration

后端 未结 9 1307
孤街浪徒
孤街浪徒 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 20:56

    A very concise way to do it using BitArray and LINQ:

    public static int Count(Skills skillsToCount)
    {
        return new BitArray(new[] {(int)skillsToCount}).OfType().Count(x => x);
    }
    

提交回复
热议问题