Sam Casil
Sam Casil

Reputation: 948

Problem on sorting an array

I have problem in sorting an array in ascending form and i don't know how to fix it.

string[] filePath = Directory.GetFiles(fbdialog.SelectedPath.ToString(), "*", SearchOption.AllDirectories);
Array.Sort(filePath);

Here are the values of an filePath.

"C:\\Documents and Settings\\20110909\\DAR-AAP070127-20110909.ods"
"C:\\Documents and Settings\\20110909\\DAR-ALA061452-09050909.xls"
"C:\\Documents and Settings\\20110819\\DAR-AAP070127-20110819.xls"

I want to look like this..

"C:\\Documents and Settings\\20110909\\DAR-AAP070127-20110909.ods"
"C:\\Documents and Settings\\20110819\\DAR-AAP070127-20110819.xls"
"C:\\Documents and Settings\\20110909\\DAR-ALA061452-09050909.xls"

Thanks in Advance.

Upvotes: 0

Views: 410

Answers (4)

Tim Lloyd
Tim Lloyd

Reputation: 38494

To sort by "EmpNo" e.g. "AAP070127":

string[] sortedFiles = Directory
    .GetFiles(fbdialog.SelectedPath, "*", SearchOption.AllDirectories)
    .OrderBy(n => Path.GetFileName(n).Split('-')[1])
    .ToArray();

Update

And without Linq as you mention using C# 2.0. The following uses a custom comparer to compare only the "EmpNo" codes in your file names. The solution expects your file names to be well-formed i.e. for them to contain an "EmpNo" in the format of your example file names.

    [Test]
    public void Sort()
    {
        string[] files = Directory
            .GetFiles(fbdialog.SelectedPath, "*", SearchOption.AllDirectories);

        Array.Sort(files, new EmpNoFileComparer());
    }

    private class EmpNoFileComparer : IComparer<string>
    {
        public int Compare(string x, string y)
        {
            string empNoX = Path.GetFileName(x).Split('-')[1];
            string empNoY = Path.GetFileName(y).Split('-')[1];

            return empNoX.CompareTo(empNoY);
        }
    }

Upvotes: 1

Ian Nelson
Ian Nelson

Reputation: 58783

Here's a version using some LINQ. Note also that if you only need the file names, not the files themselves, then DirectoryInfo.GetFiles() can be used rather than Directory.GetFiles().

var filePaths = new DirectoryInfo(fbdialog.SelectedPath.ToString())
    .GetFiles("*", SearchOption.AllDirectories)
    .OrderBy(f => f.Name)
    .Select(f => f.FullName);

Upvotes: 1

abatishchev
abatishchev

Reputation: 100368

using System.Linq; // requires .NET 3.5+

IEnumerable<string> r =
    new DirectoryInfo(fbdialog.SelectedPath) // no need for ToString()
        .GetFiles("*", SearchOption.AllDirectories)
        .Select(f => f.Name) // DAR-ALA061452-09050909.xls
        .Select(f => f.Substring(4, 9)) // ALA061452
        .OrderBy(f => f);

or shorter:

new DirectoryInfo(fbdialog.SelectedPath)
    .GetFiles("*", SearchOption.AllDirectories)
    .OrderBy(f => f.Name.Substring(4, 9));

Upvotes: 0

Snowbear
Snowbear

Reputation: 17274

Sort by filename:

var result = filePath.OrderBy(p => Path.GetFileName(p));

Upvotes: 1

Related Questions