Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all folders in specific order

Tags:

c#

base36

I have a list of folders that are organised by base36 (0-9 then a-z). Now my current implementation for reading them is to iterate over a number, convert it to base32, check if the folder exists. If it does read the data if it doesn't end.

The problem here is that there are gaps in the folder's numbers. Ex: 0,1,2,4,5,6,8,a,b,c,g,k,p

What would be the best way of iterating over them all, in the correct order (considering there can be any amount of folders)?

(Note: I can't simply get all of the directories, because they'd be ordered alphabetically. 2A for example would be placed before z)

like image 311
Blam Avatar asked Oct 19 '10 20:10

Blam


1 Answers

I would probably get all directories into memory, and then sort them rather than try to create something that would guess all possible values in order.

var names = GetAllDirectoryNames();
names.Sort(CompareNames);
foreach( var name in Names)
{
  DoSomethingWithDir(name);
}

//...

private static int CompareNames(string x, string y)
{
  if( x == null && y == null) return 0;
  if( x== null) return -1;
  if( y == null) return 1;

  var xVal = Base36Decode(x);
  var yVal = Base36Decode(y);
  if( xVal > yVal) return 1;
  if( xVal < yVal) return -1;
  return 0;
}

private long Base36Decode(string inputString)
{
    var charList = "0123456789abcdefghijklmnopqrstuvwxyz";

    inputString = Reverse(inputString.ToLower());
    long result = 0;
    int position = 0;
    foreach (char c in inputString)
    {
        result += charList.IndexOf(c) * (long)Math.Pow(36, position);
        position++;
    }
    return result;
}
like image 162
Philip Rieck Avatar answered Sep 22 '22 21:09

Philip Rieck