30 lines
		
	
	
		
			905 B
		
	
	
	
		
			C#
		
	
	
	
	
	
			
		
		
	
	
			30 lines
		
	
	
		
			905 B
		
	
	
	
		
			C#
		
	
	
	
	
	
using System;
 | 
						|
using System.Linq;
 | 
						|
using Microsoft.Extensions.Configuration;
 | 
						|
 | 
						|
namespace GerstITS.Examples.Api.Configurations
 | 
						|
{
 | 
						|
    public static class IConfigurationExtensions
 | 
						|
    {
 | 
						|
        #region Methods
 | 
						|
 | 
						|
        public static TEnum GetFlaggedEnum<TEnum>(this IConfiguration configuration, string key)
 | 
						|
            where TEnum : struct, IConvertible
 | 
						|
        {
 | 
						|
            ThrowsAnExceptionIfTypeIsNotAnEnumeration<TEnum>();
 | 
						|
 | 
						|
            return (TEnum)(object)(configuration.GetSection(key)?
 | 
						|
                    .Get<TEnum[]>() ?? Enumerable.Empty<TEnum>())
 | 
						|
                .Sum(i => (int)(object)i);
 | 
						|
        }
 | 
						|
 | 
						|
        private static void ThrowsAnExceptionIfTypeIsNotAnEnumeration<TEnum>() where TEnum : struct, IConvertible
 | 
						|
        {
 | 
						|
            if (!typeof(TEnum).IsEnum)
 | 
						|
                throw new InvalidOperationException($"{typeof(TEnum)} is not supported.");
 | 
						|
        }
 | 
						|
 | 
						|
        #endregion
 | 
						|
    }
 | 
						|
}
 |