How do I Custom Sort Directory Items


A

anonieko

I have a directory of files and I want to sort in in Array List in
a customized way. How do I do that?class main
{
static void Main(string[] args)
{
string[] items = Directory.GetFiles( "c:\dir", "*.*");
ArrayList al = new ArrayList( items);
TransIdComparerClass myComp = new TransIdComparerClass();
al.Sort(myComp);
string topFile = (string) al[0];
}
}

/// <summary>
/// For example. This IComparer is used to sort based
// on the fourth character and onwards in each filename.
/// </summary>
public class TransIdComparerClass : IComparer
{
// Calls CaseInsensitiveComparer.Compare with the parameters
reversed.
int IComparer.Compare( Object x, Object y )
{
string a = Path.GetFileName( (string) x);
string b = Path.GetFileName( (string) y);
return ( a.Substring(3).CompareTo(b.Substring(3)) );
}
}
 
Ad

Advertisements

O

Ollie Riches

check out the IComparer interface, this is eactly what it is designed for:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/
frlrfsystemcollectionsicomparerclasscomparetopic.asp

example:

public class myReverserClass : IComparer
{
// Calls CaseInsensitiveComparer.Compare with the parameters reversed.
int IComparer.Compare( Object x, Object y )
{
return( (new CaseInsensitiveComparer()).Compare( y, x ) );
}
}

--
HTH

Ollie Riches
http://www.phoneanalyser.net

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a programmer
helping programmers.

I have a directory of files and I want to sort in in Array List in
a customized way. How do I do that?class main
{
static void Main(string[] args)
{
string[] items = Directory.GetFiles( "c:\dir", "*.*");
ArrayList al = new ArrayList( items);
TransIdComparerClass myComp = new TransIdComparerClass();
al.Sort(myComp);
string topFile = (string) al[0];
}
}

/// <summary>
/// For example. This IComparer is used to sort based
// on the fourth character and onwards in each filename.
/// </summary>
public class TransIdComparerClass : IComparer
{
// Calls CaseInsensitiveComparer.Compare with the parameters
reversed.
int IComparer.Compare( Object x, Object y )
{
string a = Path.GetFileName( (string) x);
string b = Path.GetFileName( (string) y);
return ( a.Substring(3).CompareTo(b.Substring(3)) );
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top