Skip to content

Instantly share code, notes, and snippets.

@jeffjohnson9046
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffjohnson9046/2c4e35a082bb0abf74db to your computer and use it in GitHub Desktop.
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).
// 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