Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Dictionary<String,Int> to Dictionary<String,SomeEnum> using LINQ?

I'm trying to find a LINQ oneliner that takes a Dictionary<String,Int> and returns a Dictionary<String,SomeEnum>....it might not be possible, but would be nice.

Any suggestions?

EDIT: ToDictionary() is the obvious choice, but have any of you actually tried it? On a Dictionary it doesn't work the same as on a Enumerable... You can't pass it the key and value.

EDIT #2: Doh, I had a typo above this line screwing up the compiler. All is well.

like image 473
FlySwat Avatar asked Apr 04 '09 00:04

FlySwat


3 Answers

It works straight forward with a simple cast.

Dictionary<String, Int32> input = new Dictionary<String, Int32>();

// Transform input Dictionary to output Dictionary

Dictionary<String, SomeEnum> output =
   input.ToDictionary(item => item.Key, item => (SomeEnum)item.Value);

I used this test and it does not fail.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;

namespace DictionaryEnumConverter
{
    enum SomeEnum { x, y, z = 4 };

    class Program
    {
        static void Main(string[] args)
        {           
            Dictionary<String, Int32> input =
               new Dictionary<String, Int32>();

            input.Add("a", 0);
            input.Add("b", 1);
            input.Add("c", 4);

            Dictionary<String, SomeEnum> output = input.ToDictionary(
               pair => pair.Key, pair => (SomeEnum)pair.Value);

            Debug.Assert(output["a"] == SomeEnum.x);
            Debug.Assert(output["b"] == SomeEnum.y);
            Debug.Assert(output["c"] == SomeEnum.z);
        }
    }
}
like image 155
Daniel Brückner Avatar answered Oct 19 '22 09:10

Daniel Brückner


var result = dict.ToDictionary(kvp => kvp.Key,
               kvp => (SomeEnum)Enum.ToObject(typeof(SomeEnum), kvp.Value));
like image 3
Samuel Avatar answered Oct 19 '22 11:10

Samuel


var collectionNames = new Dictionary<Int32,String>();
Array.ForEach(Enum.GetNames(typeof(YOUR_TYPE)), name => 
{ 
  Int32 val = (Int32)Enum.Parse(typeof(YOUR_TYPE), name, true); 
  collectionNames[val] = name; 
}); 
like image 1
Stand__Sure Avatar answered Oct 19 '22 11:10

Stand__Sure