I got a list that contains items. They all got a ‘Sort’ column. The sort column is of type int, and it’s unique.
Scenario:
sort 1; sort 2; sort 3;
If the user moves an item up (for example sort 3) in the list (for example to position 1, which would give the sort value 1), the items that are under the one that just got moved up, have to be shifted down in the list, and the sort number should be applied accordingly. In this case all shifted items sort – 1.
So the end state of the scenario looks like this:
sort 1 was sort 3; sort 3 was sort 2; sort 3 is now sort 1;
How can i do this with LINQ?
It’s not just 3 items. It can be a lot more.
[Edit]
public ActionResult Up(int id)
{
var item = dataContext.item.FirstOrDefault(x => x.item == id);
return View(dataContext.items);
}
That might not be the easiest code to understand but I’ve tested it and it seems to work as intended.
Let’s setup some data.
First, query is split into three parts depending on positions of old and new indexes, so we can handle each case separately.
Results for moving an item down (
oldSort = 1,newSort = 3):Results for moving an item up (
oldSort = 4,newSort = 2):UPDATE: The query works by splitting a sequence into three parts
The result is the union of the parts.
UPDATE 2: The query works for any number of items and the absence of loops is intentional.
UPDATE 3: Here’s one way to make the query work with LINQ-to-Entities.
The difference is that the types are now explicitly compatible.