【问题标题】:Convert Dictionary<String,Int> to Dictionary<String,SomeEnum> using LINQ?使用 LINQ 将 Dictionary<String,Int> 转换为 Dictionary<String,SomeEnum>?
【发布时间】:2010-10-17 12:01:15
【问题描述】:

我正在尝试找到一个 LINQ oneliner,它接受 Dictionary 并返回 Dictionary....这可能是不可能的,但会很好。

有什么建议吗?

编辑:ToDictionary() 是显而易见的选择,但你们中的任何人实际尝试过吗?在字典上,它与在 Enumerable 上的工作方式不同......你不能将键和值传递给它。

编辑#2:Doh,我在这行上面有一个错字,搞砸了编译器。一切都很好。

【问题讨论】:

  • 你不能使用 Dictionary 。因为它确实实现了 IEnumerable>.
  • 我正在查看元数据。字典 : ... IEnumerable>。所以它确实实现了它。你确定你有一个 using System.Linq?

标签: c# .net linq dictionary


【解决方案1】:

只需简单的演员表即可直接工作。

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);

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

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);
        }
    }
}

【讨论】:

    【解决方案2】:
    var result = dict.ToDictionary(kvp => kvp.Key,
                   kvp => (SomeEnum)Enum.ToObject(typeof(SomeEnum), kvp.Value));
    

    【讨论】:

      【解决方案3】:
      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; 
      }); 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-05
        • 2013-07-01
        相关资源
        最近更新 更多