LINQ "GroupBy" is adding an empty object
I recently encountered a weird behaviour with LINQ and I have a hard time finding the logic behind it.
I declared a list containing 3 structures and then I applied the .GroupBy method to that list. The items get grouped but it also adds an empty structure to the list.
Here’s an example:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load Dim lstTest As New List(Of structTest) lstTest.Add(New structTest With {.intIndex = 1, .strValue = "some value"}) lstTest.Add(New structTest With {.intIndex = 1, .strValue = "some other value"}) lstTest.Add(New structTest With {.intIndex = 1, .strValue = "another value"}) Dim result As IEnumerable(Of IGrouping(Of UInteger, structTest)) = lstTest.GroupBy(Function(x) x.intIndex).ToList() End Sub Structure structTest Dim intIndex As UInteger Dim strValue As String End Structure
If I check the result variable using Visual Studio that’s what it looks like:
The .Count property is 3 but there is 4 elements in the list and the last element is an empty element.
My question is: Why is there an additional element ?