mirror of
https://github.com/ICDSystems/ICD.Common.Utils.git
synced 2026-02-15 12:45:01 +00:00
feat: Add enum extension method for cycling to next enum value
This commit is contained in:
@@ -1,4 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using ICD.Common.Properties;
|
||||
|
||||
namespace ICD.Common.Utils.Extensions
|
||||
@@ -83,5 +85,25 @@ namespace ICD.Common.Utils.Extensions
|
||||
{
|
||||
return EnumUtils.ToStringUndefined(extends);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the next defined enum value for the enum type.
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="extends"></param>
|
||||
/// <returns></returns>
|
||||
public static T CycleNext<T>(this T extends)
|
||||
where T : struct, IConvertible
|
||||
{
|
||||
if (EnumUtils.IsFlagsEnum(typeof(T)) && !EnumUtils.HasSingleFlag(extends))
|
||||
throw new InvalidOperationException(string.Format("Cannot cycle enum with multiple flags - {0}", extends));
|
||||
|
||||
IEnumerable<T> values = EnumUtils.GetValues<T>();
|
||||
IList<T> list = values as IList<T> ?? values.ToArray();
|
||||
|
||||
int index = list.BinarySearch(extends);
|
||||
|
||||
return index == list.Count - 1 ? list[0] : list[index + 1];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -349,6 +349,22 @@ namespace ICD.Common.Utils.Extensions
|
||||
|
||||
#region Binary Search
|
||||
|
||||
/// <summary>
|
||||
/// Returns the index of the item in the list.
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="extends"></param>
|
||||
/// <param name="item"></param>
|
||||
/// <returns></returns>
|
||||
[PublicAPI]
|
||||
public static int BinarySearch<T>([NotNull] this IList<T> extends, T item)
|
||||
{
|
||||
if (extends == null)
|
||||
throw new ArgumentNullException("extends");
|
||||
|
||||
return extends.BinarySearch(item, Comparer<T>.Default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the index of the item in the list.
|
||||
/// </summary>
|
||||
|
||||
Reference in New Issue
Block a user