代码之家  ›  专栏  ›  技术社区  ›  FlySwat

使用linq将dictionary<string,int>转换为dictionary<string,someEnum>

  •  11
  • FlySwat  · 技术社区  · 17 年前

    我正在尝试查找一个Linq OneLiner,它采用字典<string,int>并返回字典<string,someEnum>…,这可能不可能,但会很好。

    有什么建议吗?

    edit:toDictionary()是显而易见的选择,但你们中有人真的尝试过吗?在字典上,它的作用与在可枚举的上不一样…您不能将键和值传递给它。

    编辑2:doh,我在这行上面有一个拼写错误,把编译器搞砸了。一切都好。

    3 回复  |  直到 8 年前
        1
  •  27
  •   Daniel Brückner    17 年前

    它的工作方式很简单。

    Dictonary<String, Int32> input = new Dictionary<String, Int32>();
    
    // Fill input dictionary
    
    Dictionary<String, SomeEnum> output =
       input.ToDictionary(item => item.Key, item => (SomeEnum)item.Value);
    

    我用过这个测试,它没有失败。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Diagnostics;
    
    namespace DictonaryEnumConverter
    {
        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);
            }
        }
    }
    
        2
  •  2
  •   Samuel    17 年前
    var result = dict.ToDictionary(kvp => kvp.Key,
                   kvp => (SomeEnum)Enum.ToObject(typeof(SomeEnum), kvp.Value));
    
        3
  •  1
  •   Stand__Sure    17 年前
    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; 
    });