1

I want to add all the values from a dictionary of ints to a dictionary of strings as strings. What is the most efficient or effective way of doing this...is there a better way to write this code?

static void Main()
{
    var dictOfStrings = new Dictionary<string, string>
    {
        {"sky", "blue"},
        {"sun", "orange"},
        {"stop sign", "red"},
        {"iguana", "green"}
    };

    var dictOfNumbers = new Dictionary<int, int>
    {
        {5, 2},
        {7, 1},
        {9, 0},
        {19, -1}
    };

    foreach (var number in dictOfNumbers)
    {
        dictOfStrings.Add(number.Key.ToString(), number.Value.ToString());
    }

    foreach (var item in dictOfStrings)
    {
        Console.WriteLine(item);
    }

    Console.ReadKey();
}
Red
  • 818
  • 2
  • 14
  • 26
Jonathan Kittell
  • 7,163
  • 15
  • 50
  • 93
  • 1
    This question appears to be off-topic because it belongs to the [Code Review](http://codereview.stackexchange.com/) – Dmitry Oct 23 '14 at 21:54
  • More efficient than 3 lines of code ... You can do it with LINQ but the efficiency will be the same – mybirthname Oct 23 '14 at 21:57
  • no it will be worse if you use linq, not the same – Selman Genç Oct 23 '14 at 22:00
  • I would create a `List` or I would use a different `Collection` http://stackoverflow.com/questions/3575029/c-sharp-liststring-to-string-with-delimiter maybe a `Tuple` could work too – MethodMan Oct 23 '14 at 22:05

3 Answers3

1

More efficient than a simple loop? I don't think so, but less lines (for what it's worth):

dictOfStrings = dictOfStrings.Select(kv => kv)
  .Concat(dictOfNumbers
  .Select(kv => new KeyValuePair<string, string>(kv.Key.ToString(), kv.Value.ToString())))
  .ToDictionary(kv => kv.Key, kv => kv.Value);

Now that i've written this and compare it with your loop i would use that instead of LINQ.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

Here is an option using LINQ, but IMHO that simple loop looks easier for other developers to read and understand.

var output = dictOfStrings.Concat(dictOfNumbers.ToDictionary(item => Convert.ToString(item.Key), item => Convert.ToString(item.Value)));
kmdsax
  • 1,361
  • 9
  • 12
0

Your approach is correct; LINQ would be less efficient than a simple loop.

You could create an extension method that will Add extra entries into your Dictionary Note - if you need the string to be converted to ints instead, then you'll need to add some extra parsing logic to avoid exceptions.

// extension method
public static Dictionary<string, string> Combine(this Dictionary<string, string> strs, Dictionary<int, int> ints)
{
    foreach (var i in ints)
    {
        strs.Add(i.Key.ToString(), i.Value.ToString());
    }
    return strs;
}

// usage
strs = strs.Combine(ints);
Bret
  • 2,283
  • 4
  • 20
  • 28