SamoBellows SamoBellows - 3 years ago 183 Question

LINQ to XML, get unique node in VB.NET

I have an XML file that represents a list of books that the user has access to.

<Book Bookid="1" BookName="Book1" />
<Book Bookid="1" BookName="Book1" />
<Book Bookid="2" BookName="Book2" />
<Book Bookid="1" BookName="Book1" />

That is in an XElement named xBooks

I am trying to get each book in the XML once.

Dim DistinctBooks = (From item In xBooks.Elements("Book") Select item).Distinct()

That line doesn't seem to do anything, the value of DistinctBooks is the same as xBooks.

I have searched for the solution, but it seems everyone that is doing LINQ is doing it in C#. Even though i've found other posts in C# that should work, i'm either not translating from C# to VB correctly, or VB does things differently. can anyone bump me in the right direction to get this to work in VB?



Answer Source

Assuming this is declared:

Dim xBooks = <books>
               <Book Bookid="1" BookName="Book1"/>
               <Book Bookid="1" BookName="Book1"/>
               <Book Bookid="2" BookName="Book2"/>
               <Book Bookid="1" BookName="Book1"/>

I think you are looking for something like this:

Dim DistinctBooks = From item In xBooks.Elements("Book")
                    Select bookid = item.Attribute("Bookid").Value,
                           bookName = item.Attribute("BookName").Value

Why it did not work for you is because every node is different if you consider a set of all properties that it implements. With the above you tell it which properties you need as part of a unique key for distinct. Also notice there is no need to combine multiple styles of LINQ (query and functional), you can use word Distinct as part of the query.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download