c# - LINQ查询获取两条记录的公交车号码

标签 c# xml linq

这是我的表格示例

Busnumber   st1  st2    st3     st4     st5     st6
1           abc  xyz    hvh     cdff    dfds    dfds
2           abc  efg    vv      vhv     cfg     vvv
3           uyt  ggg    xyz     hhh     saa     pok
4           uyr  abc    xyz     iii     ppp     wer

我想在此处的单个总线编号中选择同时具有两个站点“abc”和“xyz”的所有总线编号,我想要的输出是总线编号 1 和 4

那么如何在 xml 中使用 c# 在 Windows Phone 中实现此 linq 查询 我正在尝试下面的代码

XDocument loadedCustomData = XDocument.Load("best.xml");
        var filteredData =
           from c in loadedCustomData.Descendants("record")
           ///what to do below here in were clause statement ??????
          where (string)c.Element ("st1") == froms.Text && (string)c.Element("st2") == to.Text ..........

           select new words()
           {
               Busnumber = (string)c.Element("bus")

           };
        listBox1.ItemsSource = filteredData;

我的 xml 示例

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<data-set xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<record>
    <Busnumber>1</Busnumber>
    <st1>Santacruz Depot</st1>
    <st2>abc</st2>
    <st3>Vile Parle</st3>
    <st4>Mithibai College</st4>
    <st5>xyz</st5>
    <st6>Juhu Shopping Centre</st6>
</record>
<record>
    .......
</record>

最佳答案

您可以使用此线程中解释的技术:Determine if a sequence contains all elements of another sequence using Linq

使用相同的方法检查 <record> 的列表的子项包含您要检查的所有条件。你的情况下的实现是这样的:

var criteriaArray = new string[]{ "abc", "xyz" };
var filteredData = 
        from c in Busnumber.Descendants("record")
        where !criteriaArray.Except(c.Elements().Select(o => (string)o))
                            .Any() 
        select new
        {
           Busnumber = (string)c.Element("Busnumber")
        };

您可能希望更改 where 子句以仅检查以“st”开头的子元素:

where !criteriaArray.Except(c.Elements()
                             .Where(o => o.Name.LocalName.StartsWith("st"))
                             .Select(o => (string)o))
                    .Any() 

更新:

我会尝试解释一下,我假设您已经仔细阅读了我上面链接的问题。这段代码 subset.Except(superset).Any()检查子集是否包含超集中不包含的元素。

所以这个!subset.Except(superset).Any()检查子集是否不包含未包含在超集中的元素。换句话说,子集仅包含也包含在超集中的元素。换句话说,超集包含子集的所有元素。所以这就是你想要的;检查记录节点(超集)的子节点是否包含 criteriaArray(子集)的所有成员。

关于c# - LINQ查询获取两条记录的公交车号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25259310/

相关文章:

c# - 通过 LINQ 解析 XML 时出现空引用异常

c# - 如何发出对 [mscorlib]System.Console::Write(char) 的调用?

c# - StringWriter 与 StreamWriter 包装 MemoryStream - 区别

c# - Linq 中的短期约会

php - 将 PHP 设置传递给 Javascript 的最佳方式是什么?

c# - 在 c# 中将字符串转换为 xml 会出现空白错误

java - 从 XML 中搜索和显示值 - Android Java

c# - .NET List.Distinct

c# - 链接 SelectMany 而不是使用 JOIN 语句

c# - 如何清除 Cookie 上的 HttpOnly 标志?