如何在select查询中添加where子句

时间:2012-10-18 22:46:51

标签: c# xml linq select where

<PersVeh id="V0001" LocationRef="L0001" RatedDriverRef="D0001">
  <Manufacturer>FORD</Manufacturer> 
  <Model>TAURUS SE</Model> 
  <ModelYear>2007</ModelYear> 
  <VehBodyTypeCd>PP</VehBodyTypeCd> 
  <POLKRestraintDeviceCd>E</POLKRestraintDeviceCd> 
  <EstimatedAnnualDistance>
    <NumUnits>011200</NumUnits> 
  </EstimatedAnnualDistance>
  <VehIdentificationNumber>1FAFP53U37A160207</VehIdentificationNumber> 
  <VehSymbolCd>12</VehSymbolCd> 
  <VehRateGroupInfo>
    <RateGroup>16</RateGroup> 
    <CoverageCd>COMP</CoverageCd> 
  </VehRateGroupInfo>
  <VehRateGroupInfo>
    <RateGroup>21</RateGroup> 
    <CoverageCd>COLL</CoverageCd> 
  </VehRateGroupInfo>

我是Linq的新手,我希望有人能帮助我解决一个简单的问题。

对于上面的xml示例,我使用以下代码:

var result = from item in doc.Descendants(n + "PersVeh")
             where item.Attribute("id").Value == "V0001"
             select new
             {
                RatedDriverRef = (string)item.Attribute("RatedDriverRef"),
                LocationRef = (string)item.Attribute("LocationRef"),
                ModelYear = (string)item.Element(n + "ModelYear") ?? "9999",
                VehBodyTypeCd = (string)item.Element(n + "VehBodyTypeCd") ?? "XX",
                POLKRestraintDeviceCd = (string)item.Element(n + "POLKRestraintDeviceCd") ?? "0",
                EstimatedAnnualDistance = (string)item.Element(n + "EstimatedAnnualDistance").Element(n + "NumUnits") ?? "999999",
                VehIdentificationNumber = (string)item.Element(n + "VehIdentificationNumber") ?? "VIN not found",
                VehSymbolCd = (string)item.Element(n + "VehSymbolCd") ?? "00"
             };

我遇到的问题是 VehRateGroupInfo 节点。我需要根据 CoverageCd 提取 RateGroup 号码。

换句话说,就像这样:

CompSymbol = item.Element(n + "VehRateGroupInfo").Element(n + "RateGroup").Value
             where item.Element(n + "VehRateGroupInfo").Element(n + "CoverageCd").Value == "COMP"

是否可以在select中执行此操作,还是需要单独的查询?

1 个答案:

答案 0 :(得分:0)

这是一个带有查询语法的解决方案:

CompSymbol = (from vehRateGroup in item.Descendants(n + "VehRateGroupInfo")
              where vehRateGroup.Element(n + "CoverageCd").Value == "COMP"
              select vehRateGroup.Element(n + "RateGroup").Value).Single()

以下是使用方法语法的类似解决方案:

CompSymbol = item.Descendants(n + "VehRateGroupInfo")
                 .Single(x => x.Element(n + "CoverageCd").Value == "COMP")
                 .Element(n + "RateGroup").Value
相关问题