[英]How to add comma seperated string values in dictionary type session variable
[英]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.