Werner
Werner

Reputation: 2154

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?

Upvotes: 3

Views: 293

Answers (2)

Hjalmar Z
Hjalmar Z

Reputation: 1601

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;
}

Upvotes: 3

LukeHennerley
LukeHennerley

Reputation: 6444

Use Select to bring out indexes after calling OrderBy. Select((x, i)) where i will be your index.

public class TestObject
{
  public string A { get; set; }
  public int Index { get; set; }
}
public void Example()
{
  List<TestObject> testObjects = new List<TestObject>();
  testObjects.Add(new TestObject() { A = "B" });
  testObjects.Add(new TestObject() { A = "C" });
  testObjects.Add(new TestObject() { A = "A" });
  var objects = testObjects.OrderBy(x => x.A).Select((x, i) => new TestObject() { A = x.A, Index = i });
}

Upvotes: 2

Related Questions