Understanding of linq tolookup

Dear Masters
I really appreciate Can you please explain this code of linq what is means here of tolookup
I am getting confuse please check code and I also pasted result

Private Shared Sub Sample_ToLookup_Lambda()
Dim words As String() = {“one”, “two”, “three”, “four”, “five”, “six”, _
“seven”}

Dim result = words.ToLookup(Function(w) w.Length)

For i As Integer = 1 To 5
    Debug.WriteLine([String].Format("Elements with a length of {0}:", i))
    For Each word As String In result(i)
        Debug.WriteLine(word)
    Next
Next

End SubOutput:
Elements with a length of 1:
Elements with a length of 2:
Elements with a length of 3:
one
two
six
Elements with a length of 4:
four
five
Elements with a length of 5:
three
seven

I am not understand of for each loop how they are looping

Hi, Sorry for the confusion. I should’ve looked more clearly into your question. My mind was thinking about Select function and I wrote about Select instead of Lookup. This is totally my fault.

So here is how the results object looks like when you use ToLookup.

`results = {
Lookup<int, string>.Grouping { “one”, “two”, “six” },
Lookup<int, string>.Grouping { “three”, “seven” },
Lookup<int, string>.Grouping { “four”, “five” }

}`

You can see how the results are grouped by length of their elements. You can use this to see how the For each works . When you do results(i) it returns you an array whose elements have the length equal to i.

So, if I do results(3), it will return the array

Lookup<int, string>.Grouping { "one", "two", "six" }

And if I do results(5), it will return the array

Lookup<int, string>.Grouping { "three", "seven" }

But if I do results(1), it will return an empty array:

string[0] { }

That is because there is nothing in results whose elements have length = 1.

To avoid confusions, maybe you can write your code like this:

Dim result = words.ToLookup(Function(w) w.Length)

For wordLength As Integer = 1 To 5
    Debug.WriteLine([String].Format("Elements with a length of {0}:", wordLength))
    For Each word As String In result(wordLength)
        Debug.WriteLine(word)
    Next
Next

Again, my apologies for the confusion.