Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Linq Ordering

Tags:

c#

linq

c#-3.0

I have over a thousand folders, each folder contains one or more files with the following names:

Unordered:

Alison.ext
Heather.ext
Molly.ext
Paula.ext
Sam.ext

Ordered:

Molly.ext
Sam.ext
Heather.ext
Alison.ext
Paula.ext

I would like to write an expression to sort this list as described above.

like image 902
Chris Avatar asked Jun 02 '09 21:06

Chris


3 Answers

//Creating a dictionary with the custom order
var order = "MSHAP";
var orderDict = order.Select((c,i)=>new {Letter=c, Order=i})
                     .ToDictionary(o => o.Letter, o => o.Order);

var list = new List<string>{"A.ext", "H.ext", "M.ext", "P.ext", "S.ext"};

//Ordering by the custom criteria
var result = list.OrderBy(item => orderDict[item[0]]);

Instead of calling orderDict[item[0]] you could have a nice helper method that cares for the fringe cases (non existent letters, null, and so on). But that's the idea.

like image 187
Yann Schwartz Avatar answered Nov 14 '22 04:11

Yann Schwartz


Here's a method that produces keys for ordering

public int OrderKey(string fileName)
{
  char first = fileName[0];
  int result =
     first  == 'M' ? 1 :
     first  == 'S' ? 2 :
     first  == 'H' ? 3 :
     first  == 'A' ? 4 :
     first  == 'P' ? 5 :
     6;
  return result;
}

Here's how to call it:

List<File> ordered = Files.OrderBy(f => OrderKey(f.FileName)).ToList();
like image 20
Amy B Avatar answered Nov 14 '22 03:11

Amy B


List<char> sortKeys = new List<char> { 'M', 'S', 'H', 'A', 'P' };
sortKeys.Reverse();
List<FileInfo> files = new List<FileInfo>(6);

foreach(char sortKey in sortKeys)
{
    var topFiles = files.Where(file => file.Name.StartsWith(sortKey.ToString()));
    var remainingFiles = files.Except(topFiles);
    files = topFiles.Concat(remainingFiles).ToList();
}

Untested and I'm sure there are faster ways, but at least it's with linq stuff as you asked :-)

edit: I just saw the edit on your post and now I don't have any idea anymore what you really want to do, so my code is probably useless to you..

like image 1
Thomas Stock Avatar answered Nov 14 '22 03:11

Thomas Stock