I have a very interesting LINQ question. I have a document, that I am trying to filter results on, but to filter, I am matching on a REGEX result from one element of the XML.
I have the following, working LINQ to XML to get the individual data that I’m looking for.
Dim oDocument As XDocument
oDocument = XDocument.Load("test.xml")
Dim results = (From x In oDocument.Descendants.Elements("ROW") _
Select New With {.ApplicationName = GetApplicationName(x.Element("Message")), _
.EventId = x.Element("EventId")}).Distinct
However, the .Distinct doesn’t do what I want, it still shows all combinations of “ApplicationName” and “EventId”.
What I need in the end is a distinct list of results, in a new object with the application name, and event id from the XML.
The “GetAPplicationName” is a function that parses the value looking for a regex match.
Any pointers?
Sample XML
<ROOT>
<ROW>
<EventId>1</EventId>
<CreatedTimestamp>2009-10-28</CreatedTimestamp>
<Message>There is a bunch
of
garbled
inforamtion here and I'm trying to parse out a value
Virtual Path: /MyPath then it continues on with more junk after the
message, including extra stuff
</Message>
<!--Other elements removed for brevity -->
</ROW>
<ROW>
<EventId>1</EventId>
<CreatedTimestamp>2009-10-28</CreatedTimestamp>
<Message>
There is a bunch
of
garbled
inforamtion here and I'm trying to parse out a value
Virtual Path: /MyPath then it continues on with more junk after the
message, including extra stuff
</Message>
<!--Other elements removed for brevity -->
</ROW>
</ROOT>
From here I want the distinct /MyPath and EventId (In this case 1 entry with /MyPath and 1.
My GetApplicationNameMethod, on this sample will return /MyPath
Distinct doesn’t know how to compare your items, so it returns all the items unfiltered. You should use the Distinct overload that implements IEqualityComparer. This would allow you to compare the ApplicationName and EventId properties to determine equality. However, doing so would mean having a real class, not an anonymous type. The documentation demonstrates how to achieve this in an easy to understand manner.
EDIT: I was able to use your sample with the IEqualityComparer and an EventInfo class. I added my own implementation of GetApplicationName to test.
This outputs:
The rest of the code: