将通用IDictionary转换为ASP.NET MVC IEnumerable<;选择列表项>;:选择“选定”

本文关键字:选择 列表 gt 选定 lt ASP 转换 NET MVC IEnumerable IDictionary | 更新日期: 2023-09-27 17:58:31

以下是我正在考虑的完整实现:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
namespace Utils {
    public static class IDictionaryExt {
        public static IEnumerable<SelectListItem> ToSelectListItems<T, R>(this IDictionary<T, R> dic, T selectedKey) {
            return dic.Select(x => new SelectListItem() { Text = x.Value.ToString(), Value = x.Key.ToString(), Selected=(dynamic)x.Key == (dynamic)selectedKey });
        }
    }
}

请注意使用动态强制转换的相等性检查:(dynamic)x.Key == (dynamic)selectedKey。这是检查selectedKeyx.Key之间相等性的最佳方法吗?基于@Gabe在Operator'==';可以';不能应用于类型t?,我认为是这样的:过载解析被推迟到运行时,但我们确实得到了"正常"的过载解析(即考虑ValueType s和其他具有==过载的Object s与具有默认引用相等的Object s)。

将通用IDictionary转换为ASP.NET MVC IEnumerable<;选择列表项>;:选择“选定”

处理这种情况的最佳方法是使用EqualityComparer<T>.Default

return dic.Select(x => new SelectListItem() { Text = x.Value.ToString(), Value = x.Key.ToString(), Selected= EqualityComparer<T>.Default.Equals(x.Key, selectedKey) });

如果不想使用x.Key.Equals,可以将比较拉入Func:

public static IEnumerable<SelectListItem> ToSelectListItems<T, R>(this IDictionary<T, R> dic, Func<T, bool> selectedKey)
{
    return dic.Select(x => new SelectListItem() { Text = x.Value.ToString(), Value = x.Key.ToString(), Selected = selectedKey(x.Key) });
}

然后这样称呼它:

var list = sampleDictionary.ToSelectListItems(k => k == "Some Key");