【问题标题】:LinQ XML contains in where clauseLinQ XML 包含在 where 子句中
【发布时间】:2010-07-24 21:02:30
【问题描述】:
 var geoSettings = (from c in geoFields.Elements("Maps").Elements("Map")
                              select new
                              {
                                  loc = c.Element("Location").Value
                              }).Distinct().Intersect(from p in terrainFields.Elements("Maps").Elements("Map")
                                                      select new
                                                      {
                                                          loc = p.Element("Location").Value
                                                      });

       var flightCheck = from x in baseStations.Elements("BaseStation").Elements("Station")
                         //  where (geoSettings.Location.Contains(x.Element("Location").Value))
                         select new
                         {
                             Flights = x.Element("FlightName").Value,
                             loc = x.Element("Location").Value
                         };

地图和基站都是 xml 文件。我被困在 // where(geoSettings.Location.Contains(x.Element("Location").Value)) geoSettings 是一个 IEnumerable。我怎样才能获得“位置”?

【问题讨论】:

    标签: linq-to-xml


    【解决方案1】:

    改为使用连接

    var flightCheck = from x in baseStations.Elements("BaseStation").Elements("Station")
                      join y in geoSettings.Location on x x.Element("Location").Value equals y.Value                             
                      select new
                      {
                          Flights = x.Element("FlightName").Value,
                          loc = x.Element("Location").Value
                      };
    

    这将只为您提供 x 中在 y 中有匹配元素的元素。

    【讨论】:

    • 无法以这种方式访问​​ geoSettings.Location,因为 geoSettings 的类型为 IEnumerable
    • 我使用了联接,它起作用了,感谢您的想法,但 geoSettings.Location 仍然不正确,因此我无法将您的回复标记为正确答案。
    【解决方案2】:

    geoSettings 是一个 IEnumerable。 geoSettings.loc 不是。 (我假设您的意思是loc,而不是Location,因为您的代码不包含后者...)

    所以你可以进一步理解我的意思,注意geoSettings[n].loc 是有效的,但geoSettings.loc[n] 不是。

    所以...您将需要使用Any() 而不是Contains(),如“如果我的geoSettings 元素集合中的任何内容具有匹配的位置”:

    var flightCheck = from x in baseStations.Elements("BaseStation").Elements("Station")
                      where geoSettings.Any(geo => geo.loc.Contains(x.Element("Location").Value)
                      select new
                      {
                          Flights = x.Element("FlightName").Value,
                          loc = x.Element("Location").Value
                      };
    

    旁注:如果您真的只在geoSettings 中选择一个值,而不是使其成为匿名类型的集合(具有单个属性loc),只需将其设为字符串集合并仅选择值.然后你可以使用Contains() 并省去制作一大堆新对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多