I have a dictionary like:
Dictionary<string, string> myDict = new Dictionary<string, string>
{
{ "key1", "value1,value2,value3" },
{ "key2", "value4,value5" }
}
How can I convert to a List
of KeyValuePair
of following nature:
List<KeyValuePair<string, string>> myList = n List<KeyValuePair<string, string>>
{
{ "key1", "value1" },
{ "key1", "value2" },
{ "key1", "value3" },
{ "key2", "value4" },
{ "key2", "value5" }
}
Sorry for possible unclearness in the question topic.
The key to this conversion is SelectMany
method:
var res = myDict
.SelectMany(p => p.Value.Split(',').Select(s => new KeyValuePair<string, string>(p.Key, s)))
.ToList();
Without using 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;
}
Hope helps, (btw Linq is the shortest answer)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.