这是我正在考虑的完整实现:
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
。这是检查 selectedKey
和 x.Key
之间是否相等的最佳方法吗?基于@Gabe 在 Operator '==' can't be applied to type T? 中的评论,我相信它是:重载解析被推迟到运行时,但我们确实得到了“正常”的重载解析(即考虑 ValueType
和其他 Object
与 ==
相对于具有默认引用相等性的 Object
重载)。
最佳答案
处理这种情况的最佳方法是使用 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) });
关于c# - 将通用 IDictionary 转换为 ASP.NET MVC IEnumerable<SelectListItem> : choosing the Selected item,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6271729/