Friday, October 06, 2006

Using generics and anonymous delegates to populate a drop down list from a dictionary

but mostly just testing Douglas Stockwell's plugin
    private void LoadDropDownListFromDictionary<TKey, TValue>(DropDownList ddl,
IDictionary<TKey, TValue> dict,
GetNameDelegate<TValue> getName,
ConditionDelegate<TKey> getCondition)
{
foreach (KeyValuePair<TKey, TValue> pair in dict) {
if ((getCondition == null) || (getCondition(pair.Key)))
ddl.Items.Add(new ListItem(getName(pair.Value), pair.Key.ToString()));
}
}
and yes, you can also databind it directly using the dropdownlist.DataSource,
DataTextField and DataValueField

2 comments:

James Curran said...

I'm always bothered when code does needless work, like repeating the same if() each time through a loop, as if the result is going to change:

private void LoadDropDownListFromDictionary<TKey, TValue>(DropDownList ddl,
IDictionary<TKey, TValue> dict,
GetNameDelegate<TValue> getName,
ConditionDelegate<TKey> getCondition)
{
if (getCondition == null) // for backward compatibility.
LoadDropDownListFromDictionary(ddl, dict, getName);
else
{
foreach (KeyValuePair<TKey, TValue> pair in dict)
{
if (getCondition(pair.Key))
ddl.Items.Add(new ListItem(getName(pair.Value), pair.Key.ToString()));
}
}
}

private void LoadDropDownListFromDictionary<TKey, TValue>(DropDownList ddl,
IDictionary<TKey, TValue> dict,
GetNameDelegate<TValue> getName)
{
foreach (KeyValuePair<TKey, TValue> pair in dict)
{
ddl.Items.Add(new ListItem(getName(pair.Value), pair.Key.ToString()));
}
}
}

BlackTigerX said...

you're right, in this case, I did have another overloaded method that was being used when the condition was not necesary