Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
115 views
in Technique[技术] by (71.8m points)

c# - Sort a list by a custom order

I have an array of some types

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

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

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

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

and these objects have a string property called "Type"

string linkType = links[index].Type;

If linkTypes contains the elements "dog" and "cat", my links can only have "dog" or "cat" as their type.

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

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

Can someone help me out?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...