Skip to content

Commit b8b5a96

Browse files
committed
Added "TryGetEnum" for the "IQueryCollection" interface
1 parent 0524512 commit b8b5a96

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

src/Skybrud.Essentials.AspNetCore/QueryStringExtensions.cs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
using System.Diagnostics.CodeAnalysis;
99
using Skybrud.Essentials.Strings;
1010
using System.Collections.Generic;
11+
using Skybrud.Essentials.Enums;
1112

1213
// ReSharper disable ForeachCanBePartlyConvertedToQueryUsingAnotherGetEnumerator
1314

@@ -744,6 +745,32 @@ public static List<TEnum> GetEnumList<TEnum>(this IQueryCollection? query, strin
744745
return (query?[key]).ToEnumList<TEnum>(separators);
745746
}
746747

748+
/// <summary>
749+
/// Attempts to get the enum value of type <typeparamref name="TEnum"/> from the first query string component with the specified <paramref name="key"/>.
750+
/// </summary>
751+
/// <typeparam name="TEnum">The type of the enum.</typeparam>
752+
/// <param name="query">The query string.</param>
753+
/// <param name="key">The key of the query string component.</param>
754+
/// <param name="result">When this method returns, contains the parsed <typeparamref name="TEnum"/> value if successful; otherwise, <see langword="null"/>. This parameter is passed uninitialized.</param>
755+
/// <returns><see langword="true"/> if successful; otherwise, <see langword="false"/>.</returns>
756+
public static bool TryGetEnum<TEnum>(this IQueryCollection? query, string key, out TEnum result) where TEnum : struct, Enum {
757+
result = default;
758+
return TryGetString(query, key, out string? value) && EnumUtils.TryParseEnum(value, out result);
759+
}
760+
761+
/// <summary>
762+
/// Attempts to get the enum value of type <typeparamref name="TEnum"/> from the header with the specified <paramref name="key"/>.
763+
/// </summary>
764+
/// <typeparam name="TEnum">The type of the enum.</typeparam>
765+
/// <param name="query">The query string.</param>
766+
/// <param name="key">The key of the query string component.</param>
767+
/// <param name="result">When this method returns, contains the parsed <typeparamref name="TEnum"/> value if successful; otherwise, the default value of <typeparamref name="TEnum"/>. This parameter is passed uninitialized.</param>
768+
/// <returns><see langword="true"/> if successful; otherwise, <see langword="false"/>.</returns>
769+
public static bool TryGetEnum<TEnum>(this IQueryCollection? query, string key, out TEnum? result) where TEnum : struct, Enum {
770+
result = null;
771+
return TryGetString(query, key, out string? value) && EnumUtils.TryParseEnum(value, out result);
772+
}
773+
747774
#endregion
748775

749776
/// <summary>

0 commit comments

Comments
 (0)