我是 .net 初学者。我正在阅读 XML file并在两个组合框中显示它,即 cbProduct
和 cbBrandName
我需要根据 cbProduct
中的选定文本在 cbBrandName
中显示文本。
我实现了以下代码:
DataSet ds = new DataSet();
ds.ReadXml(@"..\..\stock.xml");
cbProduct.DataSource = ds.Tables[0].DefaultView.ToTable(true, "productname");
cbProduct.DisplayMember = "productname";
cbBrandName.DataSource = ds.Tables[0].DefaultView.ToTable(true, "brandname");
cbBrandName.DisplayMember = "brandname";
上面的代码显示了 cbBrandName
中的所有文本值。如何使其仅显示链接到 cbProduct
中 xml 文件的选定“productname”列的文本值。
请帮助。
提前致谢。
最佳答案
LINQ 看起来比实际更可怕。 Anirudha 的回答中使用了它的两个部分,我将尝试解释一下。第一个是 .Select(x=>
。这意味着“对于列表中的每个事物,将其替换为某物”。x 代表列表中的每个项目。
例如:
new string[]{"a", "b", "c"}.Select(x=>x.ToUpper());
将 {"a", "b", "c"} 的数组转换为 {"A", "B", "C"} 的数组。它只是说“获取列表中的每一个东西,并通过调用 ToUpper()
将其替换为你得到的任何东西。
LINQ 的另一部分是 .Where(x=>
。它只是说“给我一个较小的列表,其中只包含此语句为真的内容”。所以
new string[]{"a", "b", "c"}.Where(x=>x == "a");
将为您提供 {"a"} 的列表。将 x == "a"
替换为 x != "b"
将为您提供 {"a", "c"} 的列表。所以在第二段代码中,你说“在我用它的产品名称替换每个项目之前,我想过滤掉任何与我想要匹配的不匹配的东西。然后我转换剩下的东西。 "
为了将这些应用到代码示例中,我将重新格式化这些行并对其进行注释。
// To set the first combo box:
cbProduct.Items.AddRange( // Add everything we produce from this to the cbProduct list
doc.Descendants("items") // For each thing that represents an "items" tag and it's subtags
.Select(x=>x.Element("productname").Value) // Transform it by getting the "productname" element and reading it's Value.
.ToArray<string>()); // Then convert that into a string[].
// To set the second combo box:
string product2Search=cbProduct.SelectedItem.ToString();// get the currently selected value of cbProduct.
cbBrandName.Items.Clear(); //clears all items in cbBrandNamedoc
cbBrandName.Items.AddRange( // Add everything we produce from this to the cbBrandName list
doc.Descendants("items") // For each thing that represents an "items" tag and it's subtags
.Where(x=>x.Element("productname").Value==product2Search) // Filter our list to only those things where the productname matches what's currently selected in cbProduct (which we just stored)
.Select(y=>y.Element("brandname").Value) // Transform it by getting the "brandname" element and reading it's Value.
.ToArray<string>()); // Then convert that into a string[]
有用吗?当我自己编写代码时,我喜欢将长 LINQ 语句拆分成这样,将它们放在不同的行中,然后我可以只读下面的行:“我得到一个列表,如果这是真的,然后根据其他内容选择在它上面,然后把它变成一个数组。”
关于c# - 根据以前的 XML 组合框选择填充组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12757461/