views:

806

answers:

4

The following Code does not compile

Dim BasicGroups As String() = New String() {"Node1", "Node2"}
Dim NodesToRemove = From Element In SchemaDoc.Root.<Group> _
                    Where Element.@Name not in BasicGroups
For Each XNode In NodesToRemove
    XNode.Remove()
Next

It is supposed to Remove any Immediate child of the rootnode which has an attribute called name whose value is Not listed in the BasicGroups StringArray.

What is the correct syntax for this task?

+3  A: 

You probably want to move the 'not' part. Eg (psuedo code)

where (not (list.Contains(foo))
leppie
So in my case .....Where Not BasicGroups.Contains(Element.@Name)... Which works Great.. Thanks.
Rory Becker
Good, I wasnt sure about the VB syntax :)
leppie
+1  A: 

If the Name attribute of the nodes to be removed can be matched using a simple pattern, the following should work:

Dim SchemaDoc As New XDocument(<Root><Group Name="Foo"/><Group Name="Node1"/>
                           <Group Name="Node2"/><Group name="Bar"/></Root>)
Dim NodesToRemove = From Element In SchemaDoc.<Root>.<Group> Where _
                           Element.@Name Like "NotNode?"
For Each XNode In NodesToRemove.ToArray()
  XNode.Remove()
Next

Do note the use of ToArray() in the enumeration of NodesToRemove: you'll need this to force evaluation of the XQuery prior to starting to modify the collection it's based on.

If this won't work, here's an alternative to using LINQ (as originally I thought that inserting 'not' into LINQ queries wouldn't work, but I was set straight by another answer -- you learn something new every day...):

Dim NodesToRemove As New Collections.ObjectModel.Collection(Of XNode)
For Each Element In SchemaDoc.<Root>.<Group>
  If Not BasicGroups.Contains(Element.@Name) Then
    NodesToRemove.Add(Element)
  End If
Next

Performance should be pretty much identical to using LINQ.

mdb
Great tip regarding ToArray - Excellent point
Rory Becker
A: 

Maybe you can try something like this

mylistWithOutUndesirebleNodes = (from b in NodeLists.Cast() where (from c in NodesToDeleteList.Cast() where c.Attributes["atributo"].Value == b.Attributes["atributo"].Value select c).Count() == 0 select b).ToList();

A: 
Dim NodesToRemove = From Element In SchemaDoc.Root.<Group> _
                    Where Not BasicGroups.Contains(Element.@Name)
Joe Chung