C# List to Enum flags

This little helper method create a Enum bit field of the requested Type and ignore invalid values and lower/upper case:

 

public static T ListToEnumFlags<T>(List<string> enumFlagsAsList) where T : struct
{
	if (!typeof(T).IsEnum)
		throw new NotSupportedException(typeof(T).Name + " is not an Enum");
	T flags;
	enumFlagsAsList.RemoveAll(c => !Enum.TryParse(c, true, out flags));
	var commaSeparatedFlags = string.Join(",", enumFlagsAsList);
	Enum.TryParse(commaSeparatedFlags, true, out flags);
	return flags;
}

Sample usage:

[Test]
public void ConvertListToEnumFlags()
{
	var stringFlags = new List<string> { "read", "Write", "invalid" };
	var permissions = ListToEnumFlags<Permission>(stringFlags);
	Assert.AreEqual(Permission.Read | Permission.Write, permissions);
}

[Flags]
public enum Permission
{
	Read = 1,
	Write = 2,
	Delete = 4
}