2009-04-04 6 views
9

मैं एक LINQ oneliner खोजने की कोशिश कर रहा हूं जो एक शब्दकोश < स्ट्रिंग, Int > लेता है और एक शब्दकोश < स्ट्रिंग, SomeEnum > देता है .... यह संभव नहीं हो सकता है, लेकिन अच्छा होगा।शब्दकोश <String,Int> शब्दकोश को <स्ट्रिंग, SomeEnum> LINQ का उपयोग करके कनवर्ट करें?

कोई सुझाव?

संपादित करें: ToDictionary() स्पष्ट विकल्प है, लेकिन क्या आपने वास्तव में इसे आजमाया है? एक शब्दकोश पर यह एक संख्यात्मक पर समान काम नहीं करता है ... आप इसे कुंजी और मान पास नहीं कर सकते हैं।

संपादित करें # 2: दोह, मेरे पास इस लाइन के ऊपर एक टाइपो था जो संकलक को खराब कर रहा था। सब ठीक हैं।

+0

फिर आप एक शब्दकोश का उपयोग नहीं किया जा सकता। क्योंकि यह * IENumerable > लागू करता है। – Samuel

+0

मैं मेटाडेटा पर सही देख रहा हूं। शब्दकोश : ... IENumerable >। तो यह * इसे लागू करता है। क्या आप वाकई एक सिस्टम का उपयोग कर रहे हैं। लिंक्स? – Samuel

उत्तर

22

यह एक साधारण कलाकार के साथ सीधे आगे काम करता है।

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
var result = dict.ToDictionary(kvp => kvp.Key, 
       kvp => (SomeEnum)Enum.ToObject(typeof(SomeEnum), kvp.Value)); 
1
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; 
}); 
संबंधित मुद्दे

 संबंधित मुद्दे