Jeremy Ahn
Jeremy Ahn

Reputation: 335

Sorting through strings in array?

Each array string represents a text file in a folder. I want the array to be sorted based on what the text file contains. How would I do that?

Upvotes: 0

Views: 441

Answers (1)

Ry-
Ry-

Reputation: 224913

You can pass a custom Comparison to Array.Sort, so just read the file there:

Array.Sort(str, Function(a, b)
                    Dim aContents As String = IO.File.ReadAllText(a)
                    Dim bContents As String = IO.File.ReadAllText(b)

                    'Compare the contents and return -1 if a < b, 0 if a = b, or 1 if a > b.
                End Function)

If efficiency is an issue there, you may want to cache the contents of each file in a Dictionary or do something similar.


Also, you can go LINQ, depending on what exactly it is in the files you need to sort by:

Dim result = str.
    Select(Function(x) New With {.File = x, .Contents = IO.File.ReadAllText(x)}).
    OrderBy(Function(y) y.Contents)

... for example.

Upvotes: 5

Related Questions