I have a directory with files with these filenames:
12.mp4
34.wmv
56.ogm
78.avi
90.m4v
In my application I list the files of the directory into a List(Of File.Info) which is indexed as default:
FileList.Item(0).Name = 12.mp4
FileList.Item(1).Name = 34.wmv
FileList.Item(2).Name = 56.ogm
FileList.Item(3).Name = 78.avi
FileList.Item(4).Name = 90.m4v
But I need to process the files by the file-extension sorted in ascending mode, so this is the Item-indexation I need:
FileList.Item(0).Name = 78.avi
FileList.Item(1).Name = 90.m4v
FileList.Item(2).Name = 12.mp4
FileList.Item(3).Name = 56.ogm
FileList.Item(4).Name = 34.wmv
How I can sort the List like that in VB.NET or C#?
var sorted = FileList.OrderBy(f => f.Extension);
If this is a List(Of
FileInfo
)
, you could use:
FileList.Sort(Function(fi1,fi2) return fi1.Extension.CompareTo(fi2.Extension))
Note that a LINQ solution would potentially be nicer if you can do this sort when you build your FileInfo
list, ie:
Dim FileList = theDirectoryInfo.GetFiles().OrderBy(Function(f) f.Extension).ToList()
However, if the list already is built, sorting in place will potentially be cleaner than using LINQ to rebuild the list then reassign.
Try this:
public class ExtComparer : IComparer<string>
{
public int Compare(string x, string y)
{
//return Path.GetExtension(x).CompareTo(Path.GetExtension(y)); or
return System.String.Compare(Path.GetExtension(x), Path.GetExtension(y), System.StringComparison.Ordinal);
}
}
Use: MyList.Sort(new ExtComparer ());
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.