Question3r
Question3r

Reputation: 3832

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?

Upvotes: 5

Views: 4710

Answers (3)

Srikanth Anusuri
Srikanth Anusuri

Reputation: 1409

Implement either the IComparer or the IComparable interface. The downside of using the IComparable is that this has to be implemented by the class which is targeted for sorting, which means that in case you want to sort it a different way elsewhere in your code, you will not be able to do so using this mechanism. On the other hand, IComparer can be decoupled from the target class and implemented in multiple ways if you choose to, and depending on the sorting criteria in different parts of your application, you could apply one of these IComparer classes as needed.

https://support.microsoft.com/en-us/help/320727/how-to-use-the-icomparable-and-icomparer-interfaces-in-visual-c

Upvotes: 0

Zohar Peled
Zohar Peled

Reputation: 82524

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

Upvotes: 7

Dave Smash
Dave Smash

Reputation: 3001

Comparisons such as "alphabetical order" (string) "bigger number" (numerical types) etc. are accomplished using the IComparable interface. You can implement this interface in your custom class to make instances sort themselves any way you like. Read up on the interface here:

https://msdn.microsoft.com/en-us/library/4d7sx9hd(v=vs.110).aspx

If you have a fixed number of types, then you could use a quick helper method to return an integer for each object depending on its type, and compare the returned integers from each object to determine which one "comes first."

Upvotes: 0

Related Questions