Created
March 26, 2018 21:03
-
-
Save dannycabrera/85415ff16a85b36a291a102a1ec20d35 to your computer and use it in GitHub Desktop.
MoveToTop Extension
This file contains 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
// 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