How to put XDocument elements into Comboboxes (second box dependent on first) (C# .net 3.5)
I'm trying to take XML and display two comboboxes. The first combobox will contain a distinct list (i.e., no duplicates) from the provinceCode elements. The second combobox will show only nameEN elements matching the provinceCode. Here is a sample of my XML:
<siteList>
<site code="s0000001">
<nameEn>Edmonton</nameEn>
<provinceCode>AB</provinceCode>
</site>
<site code="s0000002">
<nameEn>Vancouver</nameEn>开发者_高级运维
<provinceCode>BC</provinceCode>
</site>
...
</siteList>
I have my XDocument from this:
XDocument loaded = XDocument.Parse(strSiteList);
I'm struggling with how to extract the unique list of provinces. It's something like:
var list = loaded.Descendants("provinceCode").Distinct;
but I'm new to C# and XDocument and I don't know what type of variable to use so I get "Cannot assign method group to an implicitly-typed local variable".
And I'm totally in the dark on how do to the comboboxes. I've done a quick search on stackoverflow and google, but there doesn't seem to be anything relevant on both XDocument and dependent comboboxes in C#. Is using XDocument the wrong approach?
Thanks!
The problem is that you're not actually calling the method. You could write:
var list = loaded.Descendants("provinceCode").Distinct();
Note the brackets.
but I don't think that actually does what you want. I suspect you want:
List<string> list = loaded.Descendants("provinceCode")
.Select(x => x.Value)
.Distinct()
.ToList();
That will give you a list of distinct province codes as a list of strings.
It's not quite clear what you mean about the second list - is that meant to match just a single province code? If so:
List<string> names = loaded.Descendants("site")
.Where(x => x.Element("provinceCode").Value == provinceCode)
.Select(x => x.Element("nameEn").Value)
.ToList();
精彩评论