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

本文关键字:Dictionary 转换 集合 KeyValuePairs 字符串 分隔 包含 | 更新日期: 2023-09-27 18:13:19

我有一个这样的字典:

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

如何转换为以下性质的KeyValuePairList:

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

很抱歉,题目可能不清楚。

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

这个转换的关键是SelectMany方法:

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

不使用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是最短的答案)