Home > other >  How to reorder list elements by value after manually updating value of element
How to reorder list elements by value after manually updating value of element

Time:01-26

I have class called tabs in my application, and each of those tabs has its own ordinal number.

It is possbile to set ordinal number through UI and depending on how the ordinal numbers are set in same order tabs will be displayed to end user (on frontend).

public class Tab
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int Order { get; set; }
}

So basically if I have situation where I have defined 4 tabs for example:

{Id: 1, Title: First Tab, Order: 1}, 
{Id: 2, Title: Second Tab, Order: 2}, 
{Id: 3, Title: Third Tab, Order: 3}, 
{Id: 4, Title: Fourth Tab, Order: 4}

And if I decide that the tab with Id: 3 will be first tab to display, I would do something like this:

{Id: 1, Title: First Tab, Order: 1}, 
{Id: 2, Title: Second Tab, Order: 2}, 
{Id: 3, Title: Third Tab, Order: 1}, 
{Id: 4, Title: Fourth Tab, Order: 4}

as you can see now we have two tabs with Order: 1 in same array.

My question is how can I after setting Order to 1 for tab with Id: 3, recalculate tabs orders in a way: I set manually order 1, so that is new 1, tab which had order 1 now becoming 2, 3 is set manually to 1 as we said earlier, old 3 becoming 4.. Any kind of help would be awesome!

Thanks everyone in advance!

CodePudding user response:

If the order has a value and could have any other value. It could be one of those cases:

  • The order is the same: Don't do anything.
  • The order is lower, for instance, from 16 to 3. Every tab with an order from 3 to 15 must be increased. 3 becomes 4, 4 -> 5 .. 15 -> 16 and 16 becomes 3.
  • The order is higher, for instance, from 3 to 16. Every tab from 16 to 4 must be decreased. 4 becomes 3, 5 -> 4 .. 16 -> 15, and 3 becomes 16.

The algorithm you want to implement would look like this:

private void ChangeOrder(Tab tabToUpdate, int orderToGive, List<Tab> tabs)
{
    if (tabToUpdate.Order > orderToGive)
    {
        var tabsToUpdate = tabs.Where(t => t.Order >= orderToGive && t.Order < tabToUpdate.Order);
        foreach (var tab in tabsToUpdate)
        {
             tab.Order  ;
        }
    }
    else if (tabToUpdate.Order < orderToGive)
    {
        var tabsToUpdate = tabs.Where(t => t.Order <= orderToGive && t.Order > tabToUpdate.Order);
        foreach (var tab in tabsToUpdate)
        {
             tab.Order--;
        } 
    }
    tabToUpdate.Order = orderToGive;
}

You should rename the variable as you see fit. This is not the perfect algorithm of course, I only gave you the guideline.

To solve this kind of problems in the future, try to decompose the problem into smaller ones as you can see, the final algorithm is really basic.

Don't hesitate to ask me if you have any question.

  • Related