自定义Linq订购 [英] Custom Linq Ordering

查看:55
本文介绍了自定义Linq订购的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有上千个文件夹,每个文件夹包含一个或多个以下名称的文件:

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

无序:


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

已订购:


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

我想编写一个表达式来如上所述对列表进行排序.

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

推荐答案

//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]]);

代替调用orderDict [item [0]],您可以拥有一个不错的帮助程序方法,该方法可以处理边缘情况(不存在的字母,null等).但这就是主意.

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.

这篇关于自定义Linq订购的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆