Why stop there? Why not a list of triplets? Or quadruplets?
The fact is that this is very trivial to write yourself. Write a class that derives from List<KeyValuePair<TKey, TValue>>
, add an Add
method that takes 2 parameters.
public class KeyValueList<TKey, TValue> : List<KeyValuePair<TKey, TValue>>
{
public void Add(TKey key, TValue value)
{
Add(new KeyValuePair<TKey, TValue>(key, value));
}
}
Boom, you're done.
Further comments: Note that KeyValuePair<TKey, TValue>
is an immutable type (as is Tuple<T1, T2>
in .NET 4.0); so if you'd want to be able to do something like this:
list[0].Value = 5;
...then you'd need a mutable type, something like:
public sealed class Pair<T1, T2>
{
public T1 X { get; set; }
public T2 Y { get; set; }
}
public class PairList<T1, T2> : List<Pair<T1, T2>>
{ /* ...same as KeyValueList<T1, T2>, basically... */ }
Also note that this would enable nice initialization syntax:
var list = new PairList<int, string>
{
{ 1, "dan" },
{ 2, "serhio" }
};
But again, the point here is that this is very easy and very trivial and thus not really deserving of its own type in the framework. Look at it this way: can you name any type in the BCL that is essentially just another type but with one single convenience method added?
Closing comments: You have posed these questions:
- Why introduce a
List<T>
type when you could just use a T[]
array?
- Why introduce a
Dictionary<TKey, TValue>
type when you could just use a List<KeyValuePair<TKey, TValue>>
?
These are bizarre questions, honestly. Why introduce OOP at all when you can just do everything with procedural code and global variables? Why introduce higher-level programming languages like C#, C++, or even C when you could just write everything in Assembly?
The List<T>
class provides a useful encapsulation of all the functionality that goes into accessing elements in an array, maintaining the number of items, resizing the array as necessary, etc. There is a big difference between what you can do with a List<T>
and what you can do with just a T[]
.
The Dictionary<TKey, TValue>
also encapsulates the functionality of maintaining a collection of values associated with unique keys. It also provides killer O(1) lookup time on those keys. There is a huge difference between a Dictionary<TKey, TValue>
and a List<KeyValuePair<TKey, TValue>>
.
The difference between a List<KeyValuePair<TKey, TValue>>
and your proposed KeyValueList<TKey, TValue>
(as I've called it above) is practically nil. Hardly anything new is encapsulated. It just is a List<T>
. Honestly the benefit is, to me, hardly greater than adding an Int32List
type that just wraps a List<int>
.
There's just no reason to add such a type to the BCL.