Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for an alterantive to List<KeyValuePair<string, KeyValuePair<string, string>>>

Tags:

c#

.net-2.0

Ended up with this awful data structure:

List<KeyValuePair<string, KeyValuePair<string, string>>>

It's not likely to get huge (<1K I estimate) and I am gonna iterate this list over and over.

Anyone can think of some better alternative with built-in types?

like image 821
JohnIdol Avatar asked Jun 24 '09 16:06

JohnIdol


People also ask

What is the default value of KeyValuePair?

default equals to null. And default(KeyValuePair<T,U>) is an actual KeyValuePair that contains null, null .

What is the difference between KeyValuePair and dictionary C#?

KeyValuePair<TKey,TValue> is used in place of DictionaryEntry because it is generified. The advantage of using a KeyValuePair<TKey,TValue> is that we can give the compiler more information about what is in our dictionary.

Can list have key-value pair in C#?

The KeyValuePair class stores a pair of values in a single list with C#.

Can KeyValuePair have duplicate keys?

You can use List<KeyValuePair<string,int>> . This will store a list of KeyValuePair 's that can be duplicate. Save this answer.


2 Answers

The best option would be to wrap your own Tuple class, sort of like the one shipping in .NET 4.0.

Then you could have a single:

List<Tuple<string,string,string>>

This is easy enough to write in .NET 2.0 - it's basically just a triplet of values, instead of having 2 in a KeyValuePair. There is no built-in equivelent for a triplet of values in .NET 2.0, though.


Edit:

After reading your comment about querying in another post, I thought I'd mention this as well -

Even if you don't have unique values in key1, you could dramatically speed up any type of query/search by using:

Dictionary<string, List<KeyValuePair<string,string>>>

Then, instead of storing a single KeyValuePair, you could look up the list of them via the key in the first element. This would be much, much faster if you needed to find all of the elements with a given first key...

like image 118
Reed Copsey Avatar answered Oct 06 '22 00:10

Reed Copsey


struct MrStruct
{
   public string Key1,
   public string Key2,
   public string Value1
}


List<MrStruct>;

This is assuming that you are accessing the list sequentially as you did say iterate over. Potentially, other data structures could be faster for searching.

like image 44
kemiller2002 Avatar answered Oct 06 '22 00:10

kemiller2002