Dictionary append question

C

csharpula csharp

Hello,
I was wondering if there is a way in c# to append two Dictionaries of
the same type:

Dictionary<string,object> dic1 and Dictionary<string,object> dic2 into
one new Dictionary<string,object> ?

(Is there any kind of AddRange such as exisits in generic list)?

Thank you very much!
 
I

Ignacio Machin ( .NET/ C# MVP )

Hello,
I was wondering if there is a way in c# to append two Dictionaries of
the same type:

Dictionary<string,object> dic1  and Dictionary<string,object> dic2 into
one new Dictionary<string,object> ?

(Is there any kind of AddRange such as exisits in generic list)?

It's not that simple, what happens if both dics share a common key?

You could simply create one such a method though. You could even use a
delegate to defer the decision of what to do with the shared keys
 
M

Marc Gravell

You could simply create one such a method though.

And in C#3, an extension method (perhaps on IDictionary<TKey,TValue>)
would be trivial. But as Ignacio rightly says - you need to decide how
to treat conflicts. Personally I'd probably just let it blow up by
default...

Marc
 
C

csharpula csharp

Could you please explain how can I create a general method for
Dictionary (tkey,tvalue) merge?
 
M

Marc Gravell

Something like below; this specific example uses C# 3, but you can do
similar with C# 2 - you just lose the ability to use
left.AddRange(right) - you have to do SomeClass.AddRange(left,right)
[perhaps renaming the method].

Marc

using System;
using System.Collections.Generic;
using System.Xml.Linq;
static class Program
{
static void Main()
{
// dictionary
var left = new Dictionary<int, string>();
left.Add(1, "Fred");
left.Add(2, "Barney");

var right = new Dictionary<int, string>();
right.Add(3, "Wilma");
right.Add(4, "Betty");

left.AddRange(right);
}
}

public static class DictionaryExt
{
public static void AddRange<TKey, TValue>(
this IDictionary<TKey, TValue> destination,
IDictionary<TKey, TValue> values)
{
if (destination == null) throw new
ArgumentNullException("destination");
if (values == null) throw new ArgumentNullException("values");

foreach (var pair in values)
{
destination.Add(pair);
}
}
public static void Merge<TKey, TValue>(
this IDictionary<TKey, TValue> destination,
IDictionary<TKey, TValue> values)
{
if (destination == null) throw new
ArgumentNullException("destination");
if (values == null) throw new ArgumentNullException("values");

foreach (var pair in values)
{
destination[pair.Key] = pair.Value;
}
}
}
 

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