Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list and give each item a new sorting index

Lets say I have 3 menu-items. Each one have (eg) 5 links inside. So I have a something like this:

//This is just some test-code. normally i''ll get the data from a database
List<NavigationModel> navigation = new List<NavigationModel>();
Random randomInt = new Random();

for (int i = 0; i < 5; i++)
{

    NavigationModel m = new NavigationModel();
    m.MenuName = "Users";
    m.LinkName = "Link (" + i + ")";
    m.ControllerName = "AAA";
    m.ActionName = "Function" + i;
    m.SortingMenu = 5;

    navigation.Add(m);
}

for (int i = 0; i < 5; i++)
{
    NavigationModel m = new NavigationModel();
    m.MenuName = "Help";
    m.LinkName = "Link (" + i + ")";
    m.ControllerName = "BBB";
    m.ActionName = "Function" + i;
    m.SortingMenu = 10;

    navigation.Add(m);
}

for (int i = 0; i < 5; i++)
{
    NavigationModel m = new NavigationModel();
    m.MenuName = "Home";
    m.LinkName = "Link (" + i + ")";
    m.ControllerName = "CCC";
    m.ActionName = "Function" + i;
    m.SortingMenu = 2;

    navigation.Add(m);
}

navigation = navigation.OrderBy(x => x.SortingMenu).ToList();

As you can see I'll get 3 menu-items with correct sorting BUT I need the sorting started by 0 followed by 1,2 ...

How can I do this without hardcoding or a database update command?

like image 604
Werner Avatar asked Dec 18 '25 04:12

Werner


1 Answers

LukeHennerleys answer is probably of a higher standard but I would rather change the value of SortingMenu with a simple for-loop. This should do the trick if you have the list sorted already.

for (int i = 0; i < navigation.Count; i++)
{
    navigation[i].SortingMenu = i;
}
like image 132
Hjalmar Z Avatar answered Dec 19 '25 22:12

Hjalmar Z



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!