3

可以说我有 3 个菜单项。每个内部都有(例如)5个链接。所以我有这样的事情:

//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();

如您所见,我将获得 3 个正确排序的菜单项,但我需要从 0 开始排序,然后是 1,2 ...

如何在没有硬编码或数据库更新命令的情况下做到这一点?

4

2 回答 2

3

LukeHennerleys 的回答可能具有更高的标准,但我宁愿用简单的for-loop. 如果您已经对列表进行了排序,这应该可以解决问题。

for (int i = 0; i < navigation.Count; i++)
{
    navigation[i].SortingMenu = i;
}
于 2013-04-22T12:20:52.530 回答
2

用于Select调用后带出索引OrderBy。你的索引Select((x, i))在哪里。i

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 });
}
于 2013-04-22T08:29:06.843 回答