using System.Collections.Generic;
public class WatchList : IEquatable<WatchList>
public int Id { get; set; }
public string Name { get; set; }
public int UserId { get; set; }
public int Position { get; set; }
public bool Equals(WatchList other)
if (other == null) return false;
if (ReferenceEquals(this, other)) return true;
public override bool Equals(object obj)
WatchList other = obj as WatchList;
public override int GetHashCode()
public static void UpdateWatchListsSort(string userId, List<WatchList> watchListsWithModifiedPosition)
List<WatchList> allUserWatchLists = GetWatchListsFromDb(userId);
Dictionary<int, WatchList> dbWatchListIdLookup = allUserWatchLists.ToDictionary(w => w.Id);
if (watchListsWithModifiedPosition.Count == allUserWatchLists.Count)
allUserWatchLists = watchListsWithModifiedPosition;
foreach (WatchList modified in watchListsWithModifiedPosition.OrderBy(w => w.Position))
WatchList dbWatchList = dbWatchListIdLookup[modified.Id];
int newIndex = modified.Position - 1;
int oldIndex = allUserWatchLists.IndexOf(dbWatchList);
allUserWatchLists.RemoveAt(oldIndex);
bool movedForwards = newIndex > oldIndex;
allUserWatchLists.Insert(newIndex, dbWatchList);
var changeInfos = allUserWatchLists
.Select((wl, index) => new {WatchList = wl, NewPosition = index + 1})
.Where(x => x.WatchList.Position != x.NewPosition)
foreach (var change in changeInfos)
WatchList wl = change.WatchList;
wl.Position = change.NewPosition;
bool success = wl.Position == watchListsWithModifiedPosition
.Where(w => w.Id == wl.Id)
.DefaultIfEmpty(wl.Position)
Console.WriteLine("WatchLists has correct position? " + success);
bool containsDuplicatePositions = allUserWatchLists
.Count() < allUserWatchLists.Count;
Console.WriteLine("No duplicate positions? " + !containsDuplicatePositions);
private static List<WatchList> GetWatchListsFromDb(string userId)
var allDbWatchLists = new List<WatchList>
new WatchList(1) {Position = 1},
new WatchList(2) {Position = 2},
new WatchList(3) {Position = 3},
new WatchList(4) {Position = 4},
new WatchList(5) {Position = 5}
public static void Main(string[] args)
var changedWatchLists = new List<WatchList>
new WatchList(1) {Position = 5}, new WatchList(3) {Position = 1}, new WatchList(5) {Position = 4}
WatchList.UpdateWatchListsSort("123", changedWatchLists);