繁体   English   中英

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

[英]How to convert a Dictionary containing values as comma seperated strings into a Collection of 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" }
    }

很抱歉,您对问题的话题不清楚。

转换的关键是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是最短的答案)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM