score:1
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.
Dim results = (From x In doc.Descendants.Elements("ROW") _
Select New EventInfo With {.ApplicationName = GetApplicationName(x.Element("Message")), _
.EventId = x.Element("EventId")})
Console.WriteLine("Total: {0}", results.Count)
Console.WriteLine("Distinct Total: {0}", results.Distinct.Count)
Console.WriteLine("Distinct (w/comparer) Total: {0}", results.Distinct(New EventInfoComparer()).Count)
This outputs:
Total: 2
Distinct Total: 2
Distinct (w/comparer) Total: 1
The rest of the code:
' EventInfo class and comparer
Private Function GetApplicationName(ByVal element As XElement)
Return Regex.Match(element.Value, "Virtual\sPath:\s/(\w+)").Groups(1).Value
End Function
Public Class EventInfo
Private _applicationName As String
Public Property ApplicationName() As String
Get
Return _applicationName
End Get
Set(ByVal value As String)
_applicationName = value
End Set
End Property
Private _eventId As Integer
Public Property EventId() As Integer
Get
Return _eventId
End Get
Set(ByVal value As Integer)
_eventId = value
End Set
End Property
End Class
Public Class EventInfoComparer
Implements IEqualityComparer(Of EventInfo)
Public Function Equals1(ByVal x As EventInfo, ByVal y As EventInfo) As Boolean _
Implements IEqualityComparer(Of EventInfo).Equals
' Check whether the compared objects reference the same data.
If x Is y Then Return True
' Check whether any of the compared objects is null.
If x Is Nothing OrElse y Is Nothing Then Return False
' Check whether the EventInfos' properties are equal.
Return (x.ApplicationName = y.ApplicationName) AndAlso (x.EventId = y.EventId)
End Function
Public Function GetHashCode1(ByVal eventInfo As EventInfo) As Integer _
Implements IEqualityComparer(Of EventInfo).GetHashCode
' Check whether the object is null.
If eventInfo Is Nothing Then Return 0
' Get the hash code for the ApplicationName field if it is not null.
Dim hashEventInfoAppName = _
If(eventInfo.ApplicationName Is Nothing, 0, eventInfo.ApplicationName.GetHashCode())
' Get the hash code for the EventId field.
Dim hashEventInfoId = eventInfo.EventId.GetHashCode()
' Calculate the hash code for the EventInfo.
Return hashEventInfoAppName Xor hashEventInfoId
End Function
End Class
score:1
I had never noticed this before, but it seems VB's anonymous types do not override Equals()
and GetHashcode()
. As such, Distinct()
is checking reference equality. The easiest workaround is to build your own class that implements IEquatable<T>
.
score:2
Ahmad's answer is correct and I upvoted it. However, I just wanted to point out the alternative VB.NET specific syntax for your LINQ to XML query.
Dim results = From x In doc...<ROW> _
Select New EventInfo With {.ApplicationName = GetApplicationName(x.<Message>.Value, _
.EventId = x.<EventId>.Value}
This returns the same result, but if you import an xmlns, then you'll get IntelliSense for the element names this way.
Here's an article describing how to get XML IntelliSense in VB.NET:
Source: stackoverflow.com
Related Query
- LINQ to XML And Distinct Custom Class
- How to perform group by in LINQ and get a Iqueryable or a Custom Class Object?
- Count of distinct with linq to entities and custom IEqualityComparer
- Linq to XML Noob question - distinct and order by on attributes
- IEqualityComparer and Linq Distinct - Hard Code GetHashCode()
- Convert xml to custom class using lambda linq
- ASP.NET / LINQ / EF: Async on custom distinct comparer class
- Linq to Xml and custom xml entities
- Populate custom List sub class from XML document via LINQ
- LINQ / XML - Storing child nodes which have different names in a custom class
- LINQ - Entity framework code first - Grouped results to custom class
- Traverse a xml tree recursively and push element value into custom class
- Help creating an instance of a class using Linq and XML
- How to write SQL translateable linq code that groups by one property and returns distinct list
- Linq Split properties of Class and assign it to another Custom Class
- Linq to xml with missing nodes in the source XML and null-coalescing operator won't work
- Distinct by property of class with LINQ
- Differences between IEquatable<T>, IEqualityComparer<T>, and overriding .Equals() when using LINQ on a custom object collection?
- LINQ query with Distinct and Union
- LINQ Get Distinct values and fill LIST
- Using Distinct with LINQ and Objects
- LINQ and XDocument: How to create XML file?
- How do I use a custom comparer with the Linq Distinct method?
- LINQ : Distinct and Orderby
- LINQ - writing a query with distinct and orderby
- Enumerable.Empty<T>().AsQueryable(); This method supports the LINQ to Entities infrastructure and is not intended to be used directly from your code
- linq distinct and select new query
- LinQ distinct with custom comparer leaves duplicates
- LINQ to SQL - Compile error when extending data context with partial class and methods
- What is the equivalent of XML PATH and Stuff in Linq lambda expression (GROUP_CONCAT/STRING_AGG)?
More Query from same tag
- Load DataTable Using Linq - Convert C# to VB.Net
- How do I segment the elements iterated over in a foreach loop
- select multiple objects from list based on values from another list
- Whats the proper way to check to see if an entry in a db table is null?
- How should I get distinct Record in linq query
- What is the linq expression for that
- Find the depth level in parent-child hierarchy
- LINQ GroupBy on object with several levels
- translation error in translating c# to vb .net using newton.jsoft (json.net) in visual studio 2012
- Put LINQ query result to DataTable
- An alternative to LinqToRDF, a library to bring Linq to RDF data?
- XElement .Value swallows embedded XML
- XML get specific name
- How to convert this SQL statement to LINQ?
- Generic with Linq DataContext
- How to write SQL query in linq
- Update Database using EF with chunks runs very slowly
- Determine 2 diagrams relative position using LINQ
- How to generate dynamic expression with a bitwise operator and enums?
- What's the formal term for a "foldable" function?
- Implementing a custom QueryProvider with in-memory query
- How can i querying inheritance class with linq to EF
- Getting the value of a key in an AttributeCollection using LINQ
- Select random questions with where clause in linq
- c# linq statement to calculate balance over 12 months
- Finding the nth largest in an int array
- How to select rows from a DataTable where a Column value is within a List?
- where clause evaluated by if
- how to get max time from a report
- LINQ, select with only the first element of child item