2010-10-20 55 views
1

我有以下代碼:分組嵌套KEYVALUE對到字典

using System; 
using System.Collections.Generic; 
using System.Collections.ObjectModel; 
using System.Linq; 


public class Test 
{ 
    static void Main() 
    { 

     var list = new List<KeyValuePair<int, KeyValuePair<int, User>>> 
         { 
          new KeyValuePair<int, KeyValuePair<int, User>>(1,new KeyValuePair<int, User>(1,new User {FirstName = "Name1"})), 
          new KeyValuePair<int, KeyValuePair<int, User>>(1,new KeyValuePair<int, User>(1,new User {FirstName = "Name2"})), 
          new KeyValuePair<int, KeyValuePair<int, User>>(1,new KeyValuePair<int, User>(2,new User {FirstName = "Name3"})), 
          new KeyValuePair<int, KeyValuePair<int, User>>(1,new KeyValuePair<int, User>(2,new User {FirstName = "Name4"})), 
          new KeyValuePair<int, KeyValuePair<int, User>>(2,new KeyValuePair<int, User>(3,new User {FirstName = "Name5"})), 
          new KeyValuePair<int, KeyValuePair<int, User>>(2,new KeyValuePair<int, User>(3,new User {FirstName = "Name6"})), 
          new KeyValuePair<int, KeyValuePair<int, User>>(2,new KeyValuePair<int, User>(3,new User {FirstName = "Name6"})), 
          new KeyValuePair<int, KeyValuePair<int, User>>(3,new KeyValuePair<int, User>(4,new User {FirstName = "Name7"})), 
         }; 
    } 
} 
public class User 
{ 
    public string FirstName { get; set; } 
} 

以上,你可以看到有用於第一密鑰值對,並進一步有相同的密鑰多個值(在第二嵌套關鍵值對)是多個相同的鍵現在我想分組它們並將列表對象轉換爲字典,其中鍵將是相同的(1,2如上所示),但第一個值將是字典,第二個值將是集合。像這樣:

var outputNeeded = new Dictionary<int,Dictionary<int,Collection<User>>>(); 

我該怎麼做。 ??

+0

它不清楚你想輸出。請解釋一下好吧 – Neowizard 2010-10-20 14:04:10

回答

4

你可以使用LINQ:

var result = list 
    .GroupBy(
     x => x.Key, 
     x => x.Value) 
    .ToDictionary(
     g => g.Key, 
     g => g.GroupBy(
        y => y.Key, 
        y => y.Value) 
       .ToDictionary(
        h => h.Key, 
        h => new Collection<User>(h.ToList()))); 

這將創建以下層次:

 
1 
\_ 1 
| \_ Name1 
| \_ Name2 
\_ 2 
    \_ Name3 
    \_ Name4 
2 
\_ 3 
    \_ Name5 
    \_ Name6 
    \_ Name6 
3 
\_ 4 
    \_ Name7 

嵌套的字典往往不是很好用,雖然。 我可能更喜歡一個簡單的查找表:

var result = list 
    .ToLookup(
     x => Tuple.Create(x.Key, x.Value.Key), 
     x => x.Value.Value); 
+0

嗨dtb,謝謝你的回覆非常接近!我需要的最後一部分是集合而不是List。你能建議怎麼做嗎? – 2010-10-20 14:06:18

+1

@Rocky Singh:只需在收藏中包裝清單。 – dtb 2010-10-20 14:09:40

+0

感謝您的支持:) – 2010-10-20 14:54:35