I'm trying to figure out the best way to make a table arbitrarily sortable. By that I mean that the user can change the sort order of the table with no relation to the data.
To accommodate this I added a new column to the table called Rank
which should be used for sorting.
I wrote this function to change the rank of a given entity
public void ChangeRank(int id, int rank)
{
_dbSet.Find(id).Rank = rank;
// adjust ranks
var index = rank + 1;
foreach (var entity in _dbSet.Where(x => x.Rank >= rank && x.Id != id).OrderBy(x => x.Rank))
entity.Rank = index++;
_context.SaveChanges();
}
I believe, correct me if I'm wrong, that the foreach loop isn't translated into a single sql statement which is what I was hoping to do - for performance. I'm pretty sure it's possible to do in raw sql using row_number()
but I want to keep it as a LINQ query.
How would I optimize the update of rank?
Are there better ways to implement arbitrary sorting?