以下是我正在考虑的完整实施:
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
s ==
重载与Object
s的默认参考相等。)
答案 0 :(得分:4)
处理这种情况的最佳方法是使用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) });
答案 1 :(得分:1)
如果您不想使用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");