我同意 Jon Skeet 的观点。这将是一种结构更好的方法,可以将与同一个人有关的信息包装在一个单一的(例如,<Person> 实体中)。您还应该为每个州提供一些名称或ID;否则,您的分组会显得随意。
<states>
<state Name="Florida">
<Person Name="a1">
<Address>a2</Address>
</Person>
<Person Name="b1">
<Address>b2</Address>
</Person>
<Person Name="c1">
<Address>c2</Address>
</Person>
</state>
<state Name="New York">
<Person Name="aa1">
<Address>aa2</Address>
</Person>
<Person Name="bb1">
<Address>bb2</Address>
</Person>
</state>
</states>
以下是构建两级字典的方法。外部字典以州名作为关键字,并由包含居住在该州的人的字典进行赋值。内部字典以人名作为关键字,并以他们的地址为值。
XDocument document = XDocument.Parse(@"
<states>
<state Name=""Florida"">
<Person Name=""a1"">
<Address>a2</Address>
</Person>
<Person Name=""b1"">
<Address>b2</Address>
</Person>
<Person Name=""c1"">
<Address>c2</Address>
</Person>
</state>
<state Name=""New York"">
<Person Name=""aa1"">
<Address>aa2</Address>
</Person>
<Person Name=""bb1"">
<Address>bb2</Address>
</Person>
</state>
</states>");
IDictionary<string, Dictionary<string, string>> dictionary =
document.Root.Elements("state").ToDictionary(
state => state.Attribute("Name").Value,
state => state.Elements("Person").ToDictionary(
person => person.Attribute("Name").Value,
person => person.Element("Address").Value));
// To get address of "a1" living in Florida:
string addr1 = dictionary["Florida"]["a1"]; // gives "a2"
// To get address of "bb1" living in New York:
string addr2 = dictionary["New York"]["bb1"]; // gives "bb2"
因此,要获取居住在城市C 的人X 的地址,您只需要访问dictionary[C][X]。
编辑:回复评论:
您可以通过首先删除他们的条目(从内部字典中)然后重新添加它(以新名称作为键)来更改一个人的名字。
例如,将名称 "aa1" 更改为 "aa2":
Dictionary<string, string> innerDictionary = dictionary["New York"];
string address = innerDictionary["aa1"];
innerDictionary.Remove("aa1");
innerDictionary.Add("xx1", address);
也就是说,如果您经常需要更改密钥,Dictionary<TKey, TValue> 可能不是最佳结构。