[英]Convert dictionary to list collection in C#
I have a problem when trying to convert a dictionary to list.尝试将字典转换为列表时遇到问题。
Example if I have a dictionary with template string as key and string as value.例如,如果我有一个字典,模板字符串作为键,字符串作为值。 Then I wish to convert the dictionary key to list collection as a string.
然后我希望将字典键转换为列表集合作为字符串。
Dictionary<string, string> dicNumber = new Dictionary<string, string>();
List<string> listNumber = new List<string>();
dicNumber.Add("1", "First");
dicNumber.Add("2", "Second");
dicNumber.Add("3", "Third");
// So the code may something look like this
//listNumber = dicNumber.Select(??????);
To convert the Keys to a List of their own: 要将密钥转换为它们自己的列表:
listNumber = dicNumber.Select(kvp => kvp.Key).ToList();
Or you can shorten it up and not even bother using select: 或者,您可以缩短它,甚至可以不用使用select:
listNumber = dicNumber.Keys.ToList();
或者:
var keys = new List<string>(dicNumber.Keys);
如果要使用Linq,则可以使用以下代码段:
var listNumber = dicNumber.Keys.ToList();
If you want convert Keys: 如果要转换密钥:
List<string> listNumber = dicNumber.Keys.ToList();
else if you want convert Values: 否则,如果要转换值:
List<string> listNumber = dicNumber.Values.ToList();
foreach (var item in dicNumber)
{
listnumber.Add(item.Key);
}
If you want to pass the Dictionary keys collection into one method argument. 如果要将字典键集合传递给一个方法参数。
List<string> lstKeys = Dict.Keys;
Methodname(lstKeys);
-------------------
void MethodName(List<String> lstkeys)
{
`enter code here`
//Do ur task
}
List<string> keys = dicNumber.Keys.ToList();
List<string> values = keys.Select(i => dicNumber[i]).ToList();
This ensures that dicNumber[keys[index]] == values[index]
for each possible index
.这确保
dicNumber[keys[index]] == values[index]
对于每个可能的index
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.