Converting a General IDictionary to ASP.NET MVC IEnumerable <SelectListItem>: Selecting the Selected Element
Here is the full implementation that I am considering:
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 });
}
}
}
Pay attention to the equality test with dynamic shots: (dynamic)x.Key == (dynamic)selectedKey. Is this the best way to test equality between selectedKeyand x.Keyhere? Based on @ Gabe's comment in Operator '==' cannot be applied to type T? , I believe that this: overload resolution is delayed until runtime, but we get a "normal" overload resolution (that is, consider ValueTypeothers Objectwith ==overloads compared Objectto using the standard default equality).
+3
2
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");
+1