【问题标题】:Filtering XML data with LinQ使用 LinQ 过滤 XML 数据
【发布时间】:2011-04-19 14:35:11
【问题描述】:

我正在开发一个 Windows Phone 7 应用程序。

我有一个表中的 Id 列表,我想过滤一个包含有关这些表的所有信息的 XML 文件。

我有以下 C# 代码:

var filteredData = 
    from c in loadedData.Descendants("gameDescription")
    where c.Attribute("gameType").Value == gameType &&
          c.Attribute("language").Value.Equals(language)
    select new SampleData.GamesDesc()
    {
        Id = uint.Parse(c.Attribute("game_id").Value),
        . . .
    };

如果我有List<long> unfinishedGamesId。我想从 unfinishedGamesId 中获取所有没有 Id 的游戏的结果。比如:

c.Attribute("game_id").Value != unfinishedGamesId[0] &&
c.Attribute("game_id").Value != unfinishedGamesId[1] &&
...

如何将它添加到 where 子句中?

【问题讨论】:

    标签: windows-phone-7 linq-to-xml where-clause


    【解决方案1】:

    你想做什么?如果您想要包含其值在该列表中的数据,查询将是:

    var filteredData = 
        from c in loadedData.Descendants("gameDescription")
        where c.Attribute("gameType").Value == gameType &&
              c.Attribute("language").Value.Equals(language) &&
              unfinishedGamesId.Contains(c.Id)
        select new SampleData.GamesDesc()
        {
            Id = uint.Parse(c.Attribute("game_id").Value),
            . . .
        };
    

    假设 Id 值是您使用 uint.Parse 获得的值,则此代码应该可以工作:

    var filteredData = 
       from c in loadedData.Descendants("gameDescription")
       where c.Attribute("gameType").Value == gameType &&
             c.Attribute("language").Value.Equals(language) &&
             unfinishedGamesId.Contains(uint.Parse(c.Attribute("game_id").Value))
       select new SampleData.GamesDesc()
       {
           Id = uint.Parse(c.Attribute("game_id").Value),
           . . .
       };
    

    进行两次属性查找和解析效率不高,但我不知道如何解决。

    【讨论】:

    • Gotcha...因为您想要列表中没有条目的值,使用“!(unfinishedGamesId.Contains(...))”应该可以解决问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多