2009-04-04 49 views
9

Tôi đang cố gắng tìm một LINQ oneliner lấy một từ điển < String, Int > và trả về một từ điển < String, SomeEnum > .... nó có thể không được, nhưng sẽ tốt đẹp.Chuyển đổi từ điển <String,Int> sang từ điển <String, SomeEnum> bằng LINQ?

Mọi đề xuất?

CHỈNH SỬA: ToDictionary() là lựa chọn hiển nhiên, nhưng có ai trong số các bạn thực sự đã thử không? Trên một từ điển nó không hoạt động giống như trên một Enumerable ... Bạn không thể vượt qua nó chìa khóa và giá trị.

EDIT # 2: Doh, tôi đã có lỗi đánh máy trên dòng này làm hỏng trình biên dịch. Tất cả đều tốt.

+0

Bạn không thể sử dụng một từ điển sau đó. Bởi vì nó * thực hiện * thực hiện IEnumerable >. – Samuel

+0

Tôi đang tìm kiếm ngay siêu dữ liệu. Từ điển : ... IEnumerable >. Vì vậy, nó * * thực hiện nó. Bạn có chắc là bạn sử dụng System.Linq không? – Samuel

Trả lời

22

Nó hoạt động thẳng về phía trước với dàn diễn viên đơn giản.

Dictonary<String, Int32> input = new Dictionary<String, Int32>(); 

// Fill input dictionary 

Dictionary<String, SomeEnum> output = 
    input.ToDictionary(item => item.Key, item => (SomeEnum)item.Value); 

Tôi đã từng thử nghiệm này và nó không thất bại.

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; 
}); 
Các vấn đề liên quan