Syrsyrian
Syrsyrian

Reputation: 35

Query an XML using LINQ and excluding where an Attribute value is equal to that of an Element

I have a LINQ query against an XML, that gives me a list of nested lists, each sublist being a list of an elements("row") attributes.

var items = loadbodies.Descendants("row").Select(a => a.Attributes().Select(b => b.Value).ToList()).ToList();

This works as intended but, what I actually need to is query this against another list of values so as not to have sublists added where one of the elements attributes("messageID") is on the second list. I can do this for one value but need to check it against the entire second list.

The query to exclude a single sublist by a single hardcoded value from the second list is below.

var items = loadbodies.Descendants("row").Where(c => (string)c.Attribute("messageID") != "avaluefromthesecondlist").Select(a => a.Attributes().Select(b => b.Value).ToList()).ToList();

Any help would be much appreciated.

Upvotes: 1

Views: 686

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500923

Just use Contains. Note that splitting lines helps readability considerably:

var ids = ...; // Some sequence of ids, e.g. a List<string> or HashSet<string>
var items = loadbodies
      .Descendants("row")
      .Where(row => ids.Contains((string) row.Attribute("messageId")))
      .Select(a => a.Attributes()
                    .Select(b => b.Value)
                    .ToList())
      .ToList();

Note that you could use a Join call too... but so long as you've got relatively few IDs, this should be fine.

Upvotes: 1

Related Questions