在C#中获取标志中的所有组合

前言

最近在做一个导出的功能,遇到一个标志枚举的字段要导出,因为导出的数据较多,多的情况可能要大几十万条.所以枚举这个字段和列表显示的方式就不同了,毕竟要考虑到性能这一块了.

示例代码

[Flags]
public enum PeopleState:byte
{
    [Description("无")]
	None = 0,
	
	[Description("高")]
	Height = 1,
	
	[Description("富")]
	Rich  = 2 ,
	
	[Description("帅")]
	Beautiful = 4,
	
	[Description("白")]
	White = 8, 
	
}

public static class MyExtensions
{
	// 获取枚举的描述信息
	public static string GetDescription<T> (this T value) where T : Enum
	{
		var type = value.GetType();
		var memberInfo = type.GetMember (value.ToString());
		if (memberInfo.Length > 0)
		{
			var attributes = memberInfo [0].GetCustomAttributes (typeof (DescriptionAttribute), false);
			if (attributes.Length > 0)
			{
				return ((DescriptionAttribute)attributes [0]).Description;
			}
		}
		return string.Empty;
	}
}

获取标志枚举中的所有组合:

void Main()
{
	var byteValues = Enum.GetValues (typeof (PeopleState));

	var count = (int)Math.Pow (2, byteValues.Length - 1);  //计算枚举中所有组合的数量,0不算,数组的长度减1

	Dictionary<PeopleState, string> stateMap = new Dictionary<PeopleState, string> (count);

	//将单个枚举值存入字典中
	foreach (PeopleState item in byteValues)
	{
		stateMap.Add (item, item.GetDescription());
	}

	for (int i = 1; i < count; i++)
	{
		PeopleState peopleState = (PeopleState)i;
		if (!stateMap.ContainsKey (peopleState))
		{
			//计算标志枚举
			List<string> descriptions = new List<string> (8);
			foreach (PeopleState byteValue in byteValues)
			{
				if (peopleState.HasFlag (byteValue) && byteValue != PeopleState.None) //判断标志枚举的单个枚举是不是在枚举中,并获取单个枚举的描述信息
				{
					descriptions.Add (byteValue.GetDescription());
				}
			}
			stateMap.Add (peopleState, string.Join ("|", descriptions));
		}
	}

	var index = 1;
	foreach (var item in stateMap)
	{
		Console.WriteLine ($"{index}=={item.Key}==== {item.Value}");
		index += 1;
	}
}

有时候不想打开VS Studio或者VS Code的时候,可以使用LinqPad进行编写代码,还是挺方便的.看一下输出的结果:

获取标志枚举的所有组合


秋风 2024-07-28