Convert Dictionary to Dictionary using LINQ?

前端 未结 3 1401
南方客
南方客 2021-02-07 07:56

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

3条回答
  •  长情又很酷
    2021-02-07 08:52

    It works straight forward with a simple cast.

    Dictionary input = new Dictionary();
    
    // Transform input Dictionary to output Dictionary
    
    Dictionary 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 input =
                   new Dictionary();
    
                input.Add("a", 0);
                input.Add("b", 1);
                input.Add("c", 4);
    
                Dictionary 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);
            }
        }
    }
    

提交回复
热议问题