该查询从xml文件构建商品符号。

文件结构是

<Commodities>
  <Grains>
    <Commodity title="Corn" value="0" name="corn">
      <Specs>
        //other elements
        <SymbolRoot>
          <Platform value="ZC" name="globex"/>
          <Platform value="C " name="bloomberg"/>
        </SymbolRoot>
      </Specs>
      <ContractMonths firstnoticedaterule="" lasttradedaterule="The business day prior to the 15th calendar day of the contract month">
        <Month value="Mar">
         <Year value="2018" firstnoticedate="02/28/18" lasttradedate="03/14/18" dateformat="mm/dd/yy"/>
          <Year value="2019" firstnoticedate="02/28/19" lasttradedate="03/14/19" dateformat="mm/dd/yy"/>
          <Year value="2020" firstnoticedate="02/28/20" lasttradedate="03/13/20" dateformat="mm/dd/yy"/>
        </Month>
      </ContractMonths>
    </Commodity>
  </Grains>
<Commodities>


现在,我可以根据需要获得合同月份,但是我还需要传入平台的符号根。现在,它被硬编码为“ C”

private List<string> GetAllSymbolsForContractMonths(CommodityList commodity, string platform)
{
    var symCode = string.Empty;
    var yrLastDigit = DateTime.Now.Year % 10;
    //get the contract month symbol codes
    var query = _doc.Descendants("Commodity")
            .Where(c => c.Attribute("name")?.Value == commodity.ToString().ToLower())
            .Descendants("ContractMonths").Elements("Month")
            .Select(v => "C " + SymbolHelpers.GetSymbolContractMonthLetter(v.Attribute("value")?.Value) + yrLastDigit + " Comdty")
            .ToList();

    return query;
}


我知道有一些方法可以对Platform元素的value属性进行选择,并将该值设置为symCode变量,但我似乎无法正确处理。然后,我可以用变量替换硬编码。

最佳答案

将您的查询一分为二。
首先,找到商品元素。

在该元素中,找到平台符号。
然后,建立清单。

private List<string> GetTypeFromVariable(CommodityList commodity, string platform)
{
    var yrLastDigit = DateTime.Now.Year % 10;

    var commodityElement = _doc.Descendants("Commodity")
        .Where(x => x.Attribute("name")?.Value.Equals(commodity.ToString(), StringComparison.InvariantCultureIgnoreCase) ?? false)
        .Single();

    var symbol = commodityElement.Descendants("Platform")
        .Where(x => x.Attribute("name")?.Value.Equals(platform, StringComparison.InvariantCultureIgnoreCase) ?? false)
        .Single()
        .Attribute("value").Value;

    return commodityElement
        .Descendants("ContractMonths").Elements("Month")
            .Select(v => symbol + " " + SymbolHelpers.GetSymbolContractMonthLetter(v.Attribute("value")?.Value) + yrLastDigit + " Comdty")
            .ToList();
}

关于c# - 查询中的多项选择,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50381059/

10-11 02:44
查看更多