按自定义顺序对列表进行排序 [英] Sort a list by a custom order

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

问题描述

我有一些类型的数组

private string[] linkTypes = {
    "dog",
    "cat",
    // and so on ..
};

是的,我可以使用 enum ,但是在这种情况下,它必须是字符串.

Yes, I could use an enum but in this case it has to be an array of strings.

所以现在我有一个名为"LinkElement"的对象列表

So now I have a List of objects called "LinkElement"

private List<LinkElement> links = new List<LinkElement>();

并且这些对象都有一个名为"Type"的字符串属性

and these objects have a string property called "Type"

string linkType = links[index].Type;

如果linkTypes包含元素"dog"和"cat",则我的链接只能使用"dog"或"cat"作为其类型.

我想按linkTypes的顺序对链接"列表进行排序.

I want to sort the list "links" by the order of linkTypes.

意味着列表顺序首先包含类型为"dog"的链接,然后显示类型为"cat"的链接.

Means the lists order contains the links with having the type "dog" first and after that the links with the type "cat" come up.

List<LinkElement> sortedLinks = ; // sort links

for (int i = 0; i < sortedLinks.Count; i++)
{
    LinkElement currentLink = sortedLinks[i];
    Console.WriteLine(currentLink.Type);
}

// Write down dogs first, cats after

有人可以帮我吗?

推荐答案

假设 linkTypes (私有字符串数组)与 links ( LinkElement ),您可以将LINQ的OrderBy与一个简单的lambda表达式配合使用:

Assuming linkTypes (the private string array) is in the same class as links (the list of LinkElement), you can use LINQ's OrderBy with a simple lambda expression:

var sortedLinks = links.OrderBy(le => Array.IndexOf(linkTypes, le.linkType)).ToList()

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

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