Dan Granger Dan Granger - 4 months ago 13
Vb.net Question

VB.NET - Re-Arranging Data In Arrays

I'm going to try and put this as simply as possible.
I have a sentence inputted and I need to "compress" the sentence.

So far in an array I have: "Hello 0" ; "my 1" ; "name 2" ; "is 3" ; "Hello 4"
Where the word is the word inputted and the number after is its position.

I need to get it like this: "Hello 0 4" ; "my 1" ; "name 2" ; "is 3"

So basically all the same words fall together in one element of the array with its positions like above.

k = 1
y = 0
For each x in Array
tempArray = x.Split(" ")
tempWord = tempArray(0) 'Takes just word and not position after it
If tempWord = Array(k) Then
newArray(y) = x & Space(1) & tempArray(1) 'tempArray(1) being the position part
End If

This is some code I tried, but to no avail. Any help? Thanks!!


Here is another inefficient LINQ solution:

Dim myArray = {"Hello 0", "my 1", "name 2", "is 3", "Hello 4"}

Dim grouped = myArray.GroupBy(Function(s) Split(s,, 2)(0), Function(s) Split(s,, 2)(1))

Dim newArray = grouped.Select(Function(g) g.Key & " " & Join(g.ToArray)).ToArray

or with a sentence:

Dim words = "Hello my name is Hello".Split

Dim newArray = Enumerable.Range(0, Len(words)).GroupBy(Function(i) words(i),
               Function(i) i & "").Select(Function(g) g.Key & " " & Join(g.ToArray)).ToArray

Split(s,, 2) splits a string by the first space and limits the result to 2 items. If the strings always have only one space then Split(s) is enough.
The first parameter of the .GroupBy LINQ extension that I used selects the value to group by, and the second parameter selects the items for each of the groups. For example:

{1,2,2}.GroupBy(Function(i) i)

will result in a collection like this:

.Key    items
1       {1}
2       {2,2}

The .Select LINQ extension is used to convert each group to a string. For example group with .Key "Hello" and iems {"0","4"} will be "Hello" & " " & Join({"0","4"}) and result in "Hello 0 4".
The .ToArray is used to get the IEnumerable results and store them in an array. For better understanding, I recommend searching for "linq VB" and experiment with some of the examples.