generics

C

csharpula csharp

Hello,
I want to perform the follwing action with the use of generics:

Method which will append 2 dictionaries such as input will be
Dictionary <T,list<U>> d1 and Dictionary <T,list<U>> d2 .
The method will return Dictionary <T,list<U>> result.

How can I implement this using the generics?

Thanks a lot!
 
Q

qglyirnyfgfo

Something to get you started. Note that like Ignacio mentioned to you
on a previous post, the code below will explode if you have repeated
values but this hopefully will give you an idea.

class Program
{
static void Main(string[] args)
{
Dictionary<string, int> x = new Dictionary<string, int>();
x.Add("uno", 1);

Dictionary<string, int> y = new Dictionary<string, int>();
x.Add("dos", 2);

Dictionary<string, int> result = AppendDictionaries(x, y);
}

static Dictionary<TKey, TValue> AppendDictionaries<TKey,
TValue>(Dictionary<TKey, TValue> x, Dictionary<TKey, TValue> y)
{
Dictionary<TKey, TValue> newCol = new Dictionary<TKey,
TValue>();

foreach(KeyValuePair<TKey, TValue> vals in x)
{
newCol.Add(vals.Key, vals.Value);
}

foreach(KeyValuePair<TKey, TValue> vals in y)
{
newCol.Add(vals.Key, vals.Value);
}

return newCol;
}
}
 
M

Marc Gravell

Can I check? Dictionary <T,list<U>>?

That looks like a multi-map, yes? In which case, another option is
ILookup<TKey,TValue> (in .NET 3.5) which describes a one-to-many (key
to values) relationship. The default MS implementation is immutable,
but I have provided a fully read-write implementation
EditableLookup<TKey,TValue> in MiscUtil:

http://www.yoda.arachsys.com/csharp/miscutil/

This includes all the necessary methods to merge lookups (which no
longer blows up since you can have repeated values per key).

I have also replied to your other thread about AddRange. If you want
an example of merging two Dictionary<T,List<U>>s that works in 2.0,
please let me know.

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top