如何将包含值作为逗号分隔字符串的字典转换为KeyValuePairs的集合?

时间:2016-10-16 11:59:02

标签: c# linq

我有一本字典:

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

如何转换为List KeyValuePair以下性质:

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

很抱歉问题可能不清楚。

2 个答案:

答案 0 :(得分:6)

此转化的关键是SelectMany方法:

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

答案 1 :(得分: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是最简短的答案)

相关问题