C# 使用 LINQ 将 Dictionary<String,Int> 转换为 Dictionary<String,SomeEnum>?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/716170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 22:15:47  来源:igfitidea点击:

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

c#.netlinqdictionary

提问by FlySwat

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.

我试图找到一个 LINQ oneliner,它接受一个 Dictionary<String,Int> 并返回一个 Dictionary<String,SomeEnum> ......这可能是不可能的,但会很好。

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.

编辑: ToDictionary() 是显而易见的选择,但你们有没有真正尝试过?在字典上它与在 Enumerable 上的工作方式不同......您不能将键和值传递给它。

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

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

采纳答案by Daniel Brückner

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

回答by Samuel

var result = dict.ToDictionary(kvp => kvp.Key,
               kvp => (SomeEnum)Enum.ToObject(typeof(SomeEnum), kvp.Value));

回答by Stand__Sure

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