问题描述
我试图找到一个需要Dictionary< String,Int>的LINQ oneliner.并返回一个Dictionary< String,SomeEnum> ....它可能是不可能的,但是会很好.
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.
有什么建议吗?
ToDictionary()是显而易见的选择,但是你们当中有人尝试过吗?在Dictionary上,它的工作方式与在Enumerable上不一样.您不能向其传递键和值.
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.
编辑#2:哎呀,我在这行上有一个错字,搞砸了编译器.一切都很好.
EDIT #2: Doh, I had a typo above this line screwing up the compiler. All is well.
推荐答案
通过简单的强制转换即可直接使用.
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);
}
}
}
这篇关于转换字典< String,Int>到字典< String,SomeEnum>使用LINQ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!