Skip to content

Instantly share code, notes, and snippets.

@dannycabrera
Created March 26, 2018 21:03
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 dannycabrera/85415ff16a85b36a291a102a1ec20d35 to your computer and use it in GitHub Desktop.
Save dannycabrera/85415ff16a85b36a291a102a1ec20d35 to your computer and use it in GitHub Desktop.
MoveToTop Extension
// Create our model
class Model {
public int Id {get;set;}
public string Name {get;set;}
}
// Create handy extension (from: https://stackoverflow.com/a/2576736/461998)
static void MoveToTop<T>(this List<T> list, int index)
{
T item = list[index];
for (int i = index; i > 0; i--)
list[i] = list[i - 1];
list[0] = item;
}
// Initialize model
var models = new List<Model>();
models.Add(new Model() { Id=1, Name="First"});
models.Add(new Model() { Id=2, Name="Second"});
models.Add(new Model() { Id=3, Name="Third"});
// Find index for bottom item
var idx = models.FindIndex(i => i.Id==3);
// Move bottom item to top
if (idx != -1)
models.MoveToTop(idx);
// Display results
foreach (var i in models)
Console.WriteLine($"Id: {i.Id} Name: {i.Name}");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment