Broadcom
Connection Name: Local Area Connection
DHCP Enabled: No
IP address(es)
[01]: abc.de.fg.h
我想把它放到Dictionary<string, Dictionary <string, string>>
所以Broadcom将成为第一本字典中的关键,其余的将重视价值。该值应存储为字典,其中Connection Name是键,Local Area Connection是值。我该怎么做呢?我是编程新手。谢谢你的帮助。
答案 0 :(得分:8)
请自己帮忙,并为此课程使用,因为在两个月的时间内你将无法理解你的代码:
public class WhatIsThis {
private List<IPAddress> ipAddresses = new List<IPAddress>();
public string Name { get; set; }
public string ConnectionName { get; set; }
public bool DHCPEnabled { get; set; }
public List<IPAddress> IPAddresses { get return ipAddresses; }
}
现在你可以保持List<WhatIsThis>
左右。如果您只有少数几个,那么查看价值的O(n)成本可以忽略不计。如果您希望以O(1)方式按名称查找,则可以映射到字典:
var dict = listOfWhatisThis.ToDictionary(k=>k.Name, v=>v}
为您提供类型为Dictionary<string,WhatIsThis>
的词典。您如何看待,您是否会在2周内更好地理解这一点,或者更确切地说是您可怕的词典?
答案 1 :(得分:1)
http://msdn.microsoft.com/en-us/library/bb531208.aspx
var dic = new dictionary<string, dictionary <string, string>>(
{"Broadcom",
new dictionary <string, string>(
{
{"Connection Name", "Local Area Connection"},
{"DHCP Enabled", "No"},
{"IP address(es) [01]", "abc.de.fg.h"}
}
)
}
);
我唯一担心的是IP地址本身应该在连接设置中的字典中,而不是单个字符串,因此子字典需要dictionary<string, object>
。
与flq的答案类似,这是一个更全面的解决方案,它可以产生两个子句:
using System.Collections.Generic;
using System.Linq;
namespace LINQDictionaryDemo
{
public class IPAddress
{
public int Index { get; private set; }
public string Value { get; private set; }
public IPAddress(int Index, string Value)
{
this.Index = Index;
this.Value = Value;
}
}
public class NetworkConnection
{
public string Name { get; set; }
public string ConnectionName { get; set; }
public bool DHCPEnabled { get; set; }
public List<IPAddress> IPAddresses { get; set; }
public Dictionary<string, object> ToDictionary()
{
return new Dictionary<string, object>
{
{ "ConnectionName", ConnectionName }
, { "DHCPEnabled", DHCPEnabled.ToString() }
, {"IPAddresses", IPAddresses.ToDictionary(k => k.Index, v => v.Value)}
};
}
}
public static class Demo
{
public static void Run()
{
var lnc = new List<NetworkConnection>
{
new NetworkConnection
{
Name = "Broadcom",
ConnectionName = "Local Area Connection",
DHCPEnabled = false,
IPAddresses = new List<IPAddress> {new IPAddress(1, "abc.de.fg.h")}
}
};
var dic = lnc.ToDictionary(k => k.Name, v => v.ToDictionary());
}
}
}