我是C#的新手。谁能帮助我解决我的问题?
我的问题是
我有一些x变量的字典列表。我的字典看起来像下面的东西。
x = [
{
"name": "rtu_dnp3",
"ipv4": "10.46.224.109/32",
"loopback": "yes",
"sap": "1/3/1",
"type": "serial"
},
{
"name": "rtu_ea",
"ipv4": "10.46.224.109/32",
"loopback": "yes",
"sap": "1/3/2",
"type": "serial"
}
]
使用此字典,我想创建另一个字典。我在python中很容易做到这一点。
y = []
for i in x:
dict = {}
dict["name"] = i["name"]
dict["ipv4"] = i["ipv4"]
y.append(dict)
那么有人可以帮助我在C#代码中做什么吗?因此,我可以使用这些字典来创建自己的格式。
答案 0 :(得分:1)
您可以将元组用于字典,
Dictionary<string, Tuple<string, string, string, string>> yourDict = new Dictionary<string, Tuple<string, string, string, string>>();
yourDict.Add("rtu_dnp3", new Tuple<string, string, string, string>("10.46.224.109/32", "yes", "1/3/1", "serial"));
yourDict.Add("rtu_ea", new Tuple<string, string, string, string>("10.46.224.109/32", "yes", "1/3/2", "serial"));
或者您可以创建模型而不是像元组一样
Dictionary<string, YourModel> yourDict = new Dictionary<string, YourModel>();
yourDict.Add("rtu_dnp3", new YourModel("10.46.224.109/32", "yes", "1/3/1", "serial"));
yourDict.Add("rtu_ea", new YourModel("10.46.224.109/32", "yes", "1/3/2", "serial"));
public class YourModel
{
public string ipv4 { get; set; }
public string loopback { get; set; }
public string sap { get; set; }
public string type { get; set; }
public YourModel(string ipv4, string loopback, string sap, string type)
{
this.ipv4 = ipv4;
this.loopback = loopback;
this.sap = sap;
this.type = type;
}
}
在这种情况下,字符串是您的键,而YourModel是您的值
- 更新
字典保留一个TKey和一个TValue。因此,您应该使用某些结构或类(您的类或预定义的类,例如Tuple)来保留多个参数。让我们与元组示例相混淆,
您可以像这样循环复制字典,
Dictionary<string, Tuple<string, string, string, string>> yourDict = new Dictionary<string, Tuple<string, string, string, string>>();
yourDict.Add("rtu_dnp3", new Tuple<string, string, string, string>("10.46.224.109/32", "yes", "1/3/1", "serial"));
yourDict.Add("rtu_ea", new Tuple<string, string, string, string>("10.46.224.109/32", "yes", "1/3/2", "serial"));
var newDict = new Dictionary<string, Tuple<string, string, string, string>>();
foreach (var item in yourDict)
{
newDict.Add(item.Key,item.Value);
}
答案 1 :(得分:1)
考虑下一个C#
代码示例。我认为这等效于您提供的Python
代码:
var x = new List<Dictionary<string, string>>
{
new Dictionary<string, string>
{
["name"] = "rtu_dnp3",
["ipv4"] = "10.46.224.109/32",
["loopback"] = "yes",
["sap"] = "1/3/1",
["type"] = "serial"
},
new Dictionary<string, string>
{
["name"] = "rtu_ea",
["ipv4"] = "10.46.224.109/32",
["loopback"] = "yes",
["sap"] = "1/3/2",
["type"] = "serial"
}
};
var y = new List<Dictionary<string, string>>();
foreach (Dictionary<string, string> i in x)
{
var dict = new Dictionary<string, string>();
dict["name"] = i["name"];
dict["ipv4"] = i["ipv4"];
y.Add(dict);
}
这里是complete sample,它还将输出的字典列表y
打印到输出窗口。
这里是用于了解C#'s
集合List
和Dictionary
的链接。