Skip to content

Commit

Permalink
Merge pull request #1809 from Mahdigln/GetEnumFromDisplayName
Browse files Browse the repository at this point in the history
Use ConcurrentDictionary For Improving GetEnumFromDisplayName
  • Loading branch information
MaggieKimani1 authored Oct 8, 2024
2 parents 6123803 + 83c9278 commit dfd6aeb
Showing 1 changed file with 15 additions and 7 deletions.
22 changes: 15 additions & 7 deletions src/Microsoft.OpenApi/Extensions/StringExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.

using System;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Microsoft.OpenApi.Attributes;
Expand All @@ -13,6 +13,8 @@ namespace Microsoft.OpenApi.Extensions
/// </summary>
public static class StringExtensions
{
private static readonly ConcurrentDictionary<Type, ConcurrentDictionary<string, object>> EnumDisplayCache = new();

/// <summary>
/// Gets the enum value based on the given enum type and display name.
/// </summary>
Expand All @@ -21,22 +23,28 @@ public static class StringExtensions
{
var type = typeof(T);
if (!type.IsEnum)
{
return default;
}

var displayMap = EnumDisplayCache.GetOrAdd(type, _ => new ConcurrentDictionary<string, object>(StringComparer.OrdinalIgnoreCase));

if (displayMap.TryGetValue(displayName, out var cachedValue))
return (T)cachedValue;


foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.Static))
{
var displayAttribute = (DisplayAttribute)field.GetCustomAttribute(typeof(DisplayAttribute));
if (displayAttribute != null && displayAttribute.Name == displayName)
var displayAttribute = field.GetCustomAttribute<DisplayAttribute>();
if (displayAttribute != null && displayAttribute.Name.Equals(displayName, StringComparison.OrdinalIgnoreCase))
{
return (T)field.GetValue(null);
var enumValue = (T)field.GetValue(null);
displayMap.TryAdd(displayName, enumValue);
return enumValue;
}
}

return default;
}
internal static string ToFirstCharacterLowerCase(this string input)
=> string.IsNullOrEmpty(input) ? string.Empty : char.ToLowerInvariant(input[0]) + input.Substring(1);
=> string.IsNullOrEmpty(input) ? string.Empty : char.ToLowerInvariant(input[0]) + input.Substring(1);
}
}

0 comments on commit dfd6aeb

Please sign in to comment.