Reputation: 578
I want to be able to change the order using the arrows on the left and also delete specific items with the delete button on the right.
Now, I have the delete functionality in place but I'm a bit clueless on how to implement the reordering.
My entity looks like this:
public class Account
{
public Guid Id { get; set; }
public string[] Property1 { get; set; }
public string Property2 { get; set; }
public string Property3 { get; set; }
public string Property 4{ get; set; }
}
My first idea was using an int property and order after it. I could swap two int properties when an arrow is pressed. If I deleted an element it would still work and if I added a new element I had to be sure to set it to max int+1. But it seems very clumsy and not efficient. Is there any better way to implement something like this?
Upvotes: 0
Views: 43
Reputation: 645
Adding Order
column is the simpliest way you can do this.
for Adding:
//get max order
int maxOrder = context.Account.Max(r => r.Order);
var newRow = new Account{ Order = maxOrder + 1 //rest of the properties };
context.Account.Add(newRow);
//Update the rest of the rows
var rows = context.Account.Where(r => r.Order >= newRow.Order).ToList();
foreach (var row in rows)
{
row.Order++;
}
context.SaveChanges();
For delete
var rowToDelete = context.Account.FirstOrDefault(r => r.Id == idToDelete);
context.Account.Remove(rowToDelete);
//Update the rest of the rows
var rows = context.Account.Where(r => r.Order > rowToDelete.Order).ToList();
foreach (var row in rows)
{
row.Order--;
}
context.SaveChanges();
For reordering
//get rows between the current order and the new order that you want to assign
var rowsBetween = context.Account.Where(r => r.Order > Math.Min(rowToMove.Order, newOrder)
&& r.Order < Math.Max(rowToMove.Order, newOrder)).ToList();
Math.Min(rowToMove.Order, newOrder)
and Math.Max(rowToMove.Order, newOrder)
is important here because if you are moving the row up and down depending on the direction Min and Max function will work
Rest is just updated the Order in rowsBetween
foreach (var row in rowsBetween)
{
if (rowToMove.Order < newOrder)
row.Order--;
else
row.Order++;
}
Upvotes: 1