forked from linguanostra/GoogleMapsAPI.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnumExtensions.cs
More file actions
73 lines (58 loc) · 2.1 KB
/
Copy pathEnumExtensions.cs
File metadata and controls
73 lines (58 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
namespace GoogleMapsAPI.NET.Extensions
{
/// <summary>
/// Enum extensions
/// </summary>
public static class EnumExtensions
{
#region Extension methods
/// <summary>
/// Get value serialization name
/// </summary>
/// <param name="value">Value</param>
/// <returns>Result name</returns>
public static string GetSerializationName(this Enum value)
{
// Get enum attribute
var enumAttribute = value.GetCustomAttribute<EnumMemberAttribute>();
// Ensure it was found
if (enumAttribute != null)
{
return enumAttribute.Value;
}
// Not found
throw new ArgumentOutOfRangeException(nameof(value));
}
/// <summary>
/// Get custom attribute defined on given enum value
/// </summary>
/// <typeparam name="TAttribute">Attribute type</typeparam>
/// <param name="enumValue">Enum value</param>
/// <returns>Matching custom attribute. Null if attribute not found.</returns>
public static TAttribute GetCustomAttribute<TAttribute>(this Enum enumValue) where TAttribute : Attribute
{
// Get member info for enum value
var memberInfo = enumValue.GetType().GetMember(enumValue.ToString()).FirstOrDefault();
// Return attribute
return (TAttribute)memberInfo?.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault();
}
/// <summary>
/// Get ordered selected enum flags list
/// </summary>
/// <param name="value">Enum value</param>
/// <returns>Result list</returns>
public static IEnumerable<Enum> GetFlags(this Enum value)
{
return
Enum.GetValues(value.GetType())
.Cast<Enum>()
.Where(value.HasFlag)
.OrderBy(x => x.GetSerializationName());
}
#endregion
}
}