首页 > 解决方案 > 使用 Linq 对多级数据进行排序

问题描述

我有一个数据结构如下:

public class BranchLevel_1
{
    public string Name { get; set; }
    public ObservableCollection<BranchLevel_2> Children { get; set; }

    public BranchLevel_1(string name, List<BranchLevel_2> children)
    {
        this.Name = name;
        this.Children = new ObservableCollection<BranchLevel_2>(children);
    }
}

public class BranchLevel_2
{
    public ObservableCollection<BranchLevel_3> Contents { get; set; }

    public BranchLevel_2(List<string> contents)
    {
        this.Contents = new ObservableCollection<BranchLevel_3>();
        for (int i = 0; i < contents.Count; i++)
        {
            this.Contents.Add(new BranchLevel_3(contents[i]));
        }
    }
}

public class BranchLevel_3
{
    public string Content { get; set; }

    public BranchLevel_3(string text)
    {
        this.Content = text;
    }
}

在第一级对数据进行排序很容易,我可以通过以下方式轻松获得:

Level1_Data.OrderBy(item => item.Name).ToList()

但是,我坚持在第二级进行排序。BranchLevel_2 类只是存储在 BranchLevel_3 类中的项目的容器。因此,我想使用存储在 BranchLevel_2.Contents 1 .Content 值中的数据对 Level2 进行排序。这种语法对我来说似乎是正确的,我找不到问题...

  Level1_Data.Select(item_Level1 => item_Level1.Children.OrderBy(item_Level2 => item_Level2.Contents[1].Content)).ToList();  

有什么提示吗?

这是 rusult(以黄色表示的应该按字母顺序排序) 在此处输入图像描述

标签: c#linqsorting

解决方案


Why not just sort the contents before adding them to the ObservableCollection

public class BranchLevel_2
{
    public ObservableCollection<BranchLevel_3> Contents { get; set; }

    public BranchLevel_2(List<string> contents)
    {
        this.Contents = new ObservableCollection<BranchLevel_3>();
        foreach (var content in contents.OrderBy(c => c))
        {
            this.Contents.Add(new BranchLevel_3(content));
        }
    }
}

推荐阅读