I'm making a program which gets me a list, but the list is not in order. I need to list to be in order like...
1.txt
2.txt
3.txt
However, it's coming out like
2.txt
1.txt
3.txt
All in random order. I am using
foreach (var file in d.GetFiles("*.txt"))
{
tosend = tosend + file.Name + "\n";
}
I don't want a single string. After it gets the file name it's going to readtext of other files its set and add it. So like [1.txt] Text
Use LINQ:
foreach (var file in d.GetFiles("*.txt").OrderBy(x => x.Name).ToList())
{
...
}
If the files will always be a number.txt you can use
foreach (var file in d.GetFiles("*.txt").OrderBy(x => int.Parse(x.Name.Substring(0,x.Name.IndexOf(".txt"))).ToList())
{
...
}
You will want to add some error checking.
Or you can sort the array:
string[] files = d.GetFiles("*.txt")
Array.Sort(files, StringComparer.InvariantCulture);
foreach (var file in files)
{
tosend = tosend + file.Name + "\n";
}
Use Linq
// top of code file
using System.Linq;
In method:
var files = d.GetFiles("*.txt").OrderBy(file => file.Name).ToList();
or as a string as per your example
string tosend = string.Join("\n", d.GetFiles("*.txt")
.Select(file => file.Name)
.OrderBy(x => x));
This joins the returned ordered list of file names using \n
as a separator.
If you are looking for Natural sort ie
1.txt
9.txt
10.txt
you can use Interop as a quick (and may be a dirty) solution (see Natural Sort Order in C# for details)
using System.Runtime.InteropServices;
...
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string left, string right);
...
// Obtain files
var files = d.GetFiles();
// Sort files in natural order
Array.Sort(files, (left, right) => StrCmpLogicalW(left.Name, right.Name));
// combine files' names into the string
string tosend = string.Join("\n", files);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.