Last active
August 29, 2015 14:05
-
-
Save jeffjohnson9046/2c4e35a082bb0abf74db to your computer and use it in GitHub Desktop.
C# - sort a list by some arbitrary sort order (i.e. not a "typical" sort order).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// You can paste this code into IDEone (http://ideone.com) and run it. For some reason, I can never remember how to do this. | |
// Therefore, I've made this Gist. There's probably a million smarter ways to handle this situation, but this one seems to | |
// work just fine. | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
public class Test | |
{ | |
public static void Main() | |
{ | |
// A collection of photos with some sort of caption. Type describes | |
// if the photo is Main, Inside or Outside. | |
var photos = new [] { | |
new { name = "first inside", type = "i" }, | |
new { name = "second inside", type = "i" }, | |
new { name = "I should be first", type = "m" }, | |
new { name = "third inside", type = "i" }, | |
new { name = "first outside", type = "o" }, | |
new { name = "second outside", type = "o" }, | |
new { name = "fourth inside", type = "i" } | |
}; | |
// Describe the desired sort order - Main should be first, | |
// then Outside photos, finally Inside photos. | |
var sortOrder = new Dictionary<string, byte>() { | |
{ "m", 0 }, // Main | |
{ "o", 1 }, // Outside | |
{ "i", 2 } // Inside | |
}; | |
// Sort the photos by the specified sort order. | |
var sortedPhotos = photos.OrderBy(x => sortOrder[x.type]); | |
// View the results. | |
foreach (var p in sortedPhotos) | |
{ | |
Console.WriteLine(p.name); | |
} | |
} | |
} | |
// Output: | |
// I should be first | |
// first outside | |
// second outside | |
// first inside | |
// second inside | |
// third inside | |
// fourth inside |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment