using Microsoft.AspNetCore.Mvc.Rendering; using Nop.Core; using Nop.Core.Infrastructure; using Nop.Services.Localization; namespace Nop.Services; /// /// Extensions /// public static class Extensions { /// /// Convert to select list /// /// Enum type /// Enum /// Mark current value as selected /// Values to exclude /// Localize /// /// A task that represents the asynchronous operation /// The task result contains the selectList /// public static async Task ToSelectListAsync(this TEnum enumObj, bool markCurrentAsSelected = true, int[] valuesToExclude = null, bool useLocalization = true) where TEnum : struct { if (!typeof(TEnum).IsEnum) throw new ArgumentException("An Enumeration type is required.", nameof(enumObj)); var localizationService = EngineContext.Current.Resolve(); var values = await Enum.GetValues(typeof(TEnum)).OfType().Where(enumValue => valuesToExclude == null || !valuesToExclude.Contains(Convert.ToInt32(enumValue))) .SelectAwait(async enumValue => new { ID = Convert.ToInt32(enumValue), Name = useLocalization ? await localizationService.GetLocalizedEnumAsync(enumValue) : CommonHelper.SplitCamelCaseWord(enumValue.ToString()) }).ToListAsync(); object selectedValue = null; if (markCurrentAsSelected) selectedValue = Convert.ToInt32(enumObj); return new SelectList(values, "ID", "Name", selectedValue); } /// /// Convert to select list /// /// Type /// List of objects /// Selector for name /// SelectList public static SelectList ToSelectList(this T objList, Func selector) where T : IEnumerable { return new SelectList(objList.Select(p => new { ID = p.Id, Name = selector(p) }), "ID", "Name"); } /// /// Convert to lookup-like dictionary, for JSON serialization /// /// Source type /// Key type /// Value type /// List of objects /// A key-selector function /// A value-selector function /// A dictionary with values grouped by key public static IDictionary> ToGroupedDictionary( this IEnumerable xs, Func keySelector, Func valueSelector) { var result = new Dictionary>(); foreach (var x in xs) { var key = keySelector(x); var value = valueSelector(x); if (result.TryGetValue(key, out var list)) list.Add(value); else result[key] = new List { value }; } return result; } /// /// Convert to lookup-like dictionary, for JSON serialization /// /// Source type /// Key type /// List of objects /// A key-selector function /// A dictionary with values grouped by key public static IDictionary> ToGroupedDictionary( this IEnumerable xs, Func keySelector) { return xs.ToGroupedDictionary(keySelector, x => x); } }