Here's a question that I always come back too every so often:
What's the best <string, string>
Collection to use, for some xyz situation (most often to bind to a DropDownList
) ?
Does anyone have a cheat sheet for this? a comprehensive list of distinctions between the various options?
If you're binding to a dropdown list, you probably have a sort order in mind and the size of the collection will (most likely and in most use cases) be small enough to avoid performance concerns. In these cases, a List<KeyValuePair<string, string>>
is a pretty easy choice, although a BindingList
might work better for binding, especially in WPF.
Tuple<string, string>
can replace KeyValuePair
even.
Furthermore, the non-generic (not strong typed) collections often give some of the worst performance with boxing (on top of being unwieldy to work with) and if you're worried about list overhead, you can specify a maximum size on creation to minimize that. Another advantage of the generic classes is that they implement IEnumerable
for use with Linq and, in my experience, tend to be more widely used and better known to your colleagues. In general, there should be 1 obvious way to do something in a language and the .Net community has chosen Dictionary<string, string>
over StringDictionary
.
You can also add extension methods to make basic lists more convenient:
public static class ListKeyValuePairExtensions
{
public static void Add<S, T>(this List<KeyValuePair<S, T>> list, S key, T value)
{
list.Add(new KeyValuePair<S, T>(key, value));
}
}
Edit: As pointed out by Porges, in cases addressed by this question, the performance hit of non-generic structures is not from boxing and unboxing, there is still a performance hit however, see this article for a quick benchmark.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With