2016-10-16 44 views
1

我有一個像一本字典:如何將包含值的字典轉換爲逗號分隔字符串到KeyValuePairs的集合?

Dictionary<string, string> myDict = new Dictionary<string, string> 
    { 
     { "key1", "value1,value2,value3" }, 
     { "key2", "value4,value5" } 
    } 

我怎麼能轉換成之後自然KeyValuePair一個List

List<KeyValuePair<string, string>> myList = n List<KeyValuePair<string, string>> 
    { 
     { "key1", "value1" }, 
     { "key1", "value2" }, 
     { "key1", "value3" }, 
     { "key2", "value4" }, 
     { "key2", "value5" } 
    } 

很抱歉的問題主題中可能不清晰。

+0

嘗試這種情況:列表> myList中= myDict。 Keys.Select(x => myDict [x] .Split(new char [] {','})。Select(y => new KeyValuePair (x,y)))。SelectMany(y => Y).ToList(); – jdweng

回答

6

這一轉換的關鍵是SelectMany方法:

var res = myDict 
    .SelectMany(p => p.Value.Split(',').Select(s => new KeyValuePair<string, string>(p.Key, s))) 
    .ToList(); 
+0

它不會編譯 –

+0

現在它的工作正常。 –

1

不使用LINQ,

public List<KeyValuePair<string, string>> GenerateKeyValuePair(Dictionary<string,string> dict) { 
     List<KeyValuePair<string, string>> List = new List<KeyValuePair<string, string>>(); 
     foreach (var item in dict) 
     { 
       string[] values = item.Value.Split(','); 
       for (int i = 0; i < values.Length; i++) 
       { 
        List.Add(new KeyValuePair<string, string>(item.Key, values[i].ToString())); 
       } 
     } 
     return List; 
    } 

希望幫助,(順便說一句LINQ的是最短的答案)

+0

'if(item.Value.Contains(','))'是無用的。你可以完全刪除'if',你的代碼也可以正常工作 –

+0

@KooKiz好點,謝謝:) – Berkay

0

你需要的是過載SelectMany,它在內部運行兩個foreach循環,並具有O(N^2)複雜性並如預期創建一個扁平結果集。以下是溶液(從接受的解決方案不同):

var result = myDict.SelectMany(x => x.Value.Split(','), 
           (x,y) => new KeyValuePair<string,string>(x.Key,y) 
          ) 

過載的SelectManyReference Link

public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(this IEnumerable<TSource> source, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector) 
     { 
      if (source == null) throw Error.ArgumentNull("source"); 
      if (collectionSelector == null) throw Error.ArgumentNull("collectionSelector"); 
      if (resultSelector == null) throw Error.ArgumentNull("resultSelector"); 
      return SelectManyIterator<TSource, TCollection, TResult>(source, collectionSelector, resultSelector); 
     } 

     static IEnumerable<TResult> SelectManyIterator<TSource, TCollection, TResult>(IEnumerable<TSource> source, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector) 
     { 
      foreach (TSource element in source) 
      { 
       foreach (TCollection subElement in collectionSelector(element)) 
       { 
        yield return resultSelector(element, subElement); 
       } 
      } 
     } 
相關問題