Custom Linq Ordering

前端 未结 5 1492
小蘑菇
小蘑菇 2021-02-09 00:34

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         


        
5条回答
  •  日久生厌
    2021-02-09 01:05

    //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{"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.

提交回复
热议问题