Yan*_*rtz 14
//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]]);
Run Code Online (Sandbox Code Playgroud)
而不是调用orderDict [item [0]],你可以有一个很好的帮助方法来处理边缘情况(不存在的字母,null等).但那是个主意.
这是一个生成订购密钥的方法
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;
}
Run Code Online (Sandbox Code Playgroud)
以下是如何调用它:
List<File> ordered = Files.OrderBy(f => OrderKey(f.FileName)).ToList();
Run Code Online (Sandbox Code Playgroud)