Reputation: 365
I have list(of string) like this:
C:\Users\..\Documents\abc_1.1.pdf ->file name abc
C:\Users\..\Documents\abc_1.2.pdf
C:\Users\..\Documents\abc_2.1.pdf
C:\Users\..\Documents\xxxxxx_1.1.pdf ->file name xxxxxx
C:\Users\..\Documents\xxxxxx_2.1.pdf
How can I use linq and group these file into groups if file has same name.
such as ex above, I want to get 2 groups, so I use the following code:
listfile.GroupBy(Function(filepath) As String
Dim filename = Path.GetFileNameWithoutExtension(filepath)
Return Regex.Match(filename , ".+(?=_\d+\.\d+)").Value.ToString()
End Function)
But this return result is all files. Can I get collect subsets?
Upvotes: 0
Views: 345
Reputation: 15101
I split the stings by the underscore and selected the first element. Then applied the Distinct
method
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lst As New List(Of String)
lst.Add("C:\Users\..\Documents\abc_1.1.pdf") '->file name abc
lst.Add("C:\Users\..\Documents\abc_1.2.pdf")
lst.Add("C:\Users\..\Documents\abc_2.1.pdf")
lst.Add("C:\Users\..\Documents\xxxxxx_1.1.pdf") '->file name xxxxxx
lst.Add("C:\Users\..\Documents\xxxxxx_2.1.pdf")
Dim newList = (From s In lst
Select s.Split("_"c)(0)).ToList.Distinct
For Each s In newList
Debug.Print(s)
Next
End Sub
'Prints
'C:\Users\..\Documents\abc
'C:\Users\..\Documents\xxxxxx
Upvotes: 2