Jump to content

sort array C#


joecool2005

Recommended Posts

HiI want to sort an array but it did not work

<% @Page Language="C#" %><% @Import Namespace="System.IO" %><script language="C#" runat="server">DirectoryInfo di = new DirectoryInfo(@"D:\Ufile\www\code");FileInfo[] rgFiles = di.GetFiles("*");Array.Sort(rgFiles) </script>

Link to comment
Share on other sites

HiI want to sort an array but it did not work
<% @Page Language="C#" %><% @Import Namespace="System.IO" %><script language="C#" runat="server">DirectoryInfo di = new DirectoryInfo(@"D:\Ufile\www\code");FileInfo[] rgFiles = di.GetFiles("*");Array.Sort(rgFiles) </script>

The FileInfo class doesn't implement the IComparable interface, so you can't use the Array.Sort method directly on it. You have to create your own class and implement the IComparer interface (<--- you won't implement the IComparable interface because FileInfo isn't inheritable).Create a class called SortFileInfo:
Imports System.IOPublic Class SortFileInfo	Implements IComparer	Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare		Dim file1, file2 As FileInfo		file1 = CType(x, FileInfo)		file2 = CType(y, FileInfo)		'change the .Name attribute if you want to sort by any other property		Return String.Compare(file1.Name, file2.Name)	End FunctionEnd Class

Now you can sort your array based on name:

		Dim di As New DirectoryInfo("C:\")		Dim rgFiles As FileInfo()		rgFiles = di.GetFiles("*")		Array.Sort(rgFiles, New SortFileInfo)		For Each file As FileInfo In rgFiles			TextBox1.AppendText(file.Name)			TextBox1.AppendText(vbNewLine)		Next

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...