按外部排序顺序对通用列表进行排序 [英] Sorting a generic list by an external sort order

查看:88
本文介绍了按外部排序顺序对通用列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用列表

简化示例

var list = new List<string>()
  {
    "lorem1.doc",
    "lorem2.docx",
    "lorem3.ppt",
    "lorem4.pptx",
    "lorem5.doc",
    "lorem6.doc",
  };

我想做的是根据外部列表排序对这些项目进行排序

What I would like to do is to sort these items based on an external list ordering

例如

var sortList = new[] { "pptx", "ppt", "docx", "doc" };

// Or
var sortList = new List<string>() { "pptx", "ppt", "docx", "doc" };

linq内置了什么可以帮助我实现这一目标的工具,还是我必须走foreach的方式?

Is there anything built-in to linq that could help me achieve this or do I have to go the foreach way?

推荐答案

使用列表,您可以将IndexOf用于Enumerable.OrderBy:

With the list you can use IndexOf for Enumerable.OrderBy:

var sorted = list.OrderBy(s => sortList.IndexOf(Path.GetExtension(s)));

因此,sortList中扩展名的索引确定了另一个列表中的优先级.未知扩展名的优先级最高,因为它们的索引为-1.

So the index of the extension in the sortList determines the priority in the other list. Unknown extensions have highest priority since their index is -1.

但是您需要在扩展名中添加一个点才能使其正常工作:

But you need to add a dot to the extension to get it working:

var sortList = new List<string>() { ".pptx", ".ppt", ".docx", ".doc" };

如果这不是一种选择,则您必须摆弄SubstringRemove,例如:

If that's not an option you have to fiddle around with Substring or Remove, for example:

var sorted = list.OrderBy(s => sortList.IndexOf(Path.GetExtension(s).Remove(0,1)));

这篇关于按外部排序顺序对通用列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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