使用Linq对多级数据进行排序

时间:2019-04-29 13:42:32

标签: c# linq sorting

我的数据结构如下:

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

有任何提示吗?

这里是粗鲁的(黄色表示应该按字母顺序排序) enter image description here

2 个答案:

答案 0 :(得分:0)

为什么不先将内容添加到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));
        }
    }
}

答案 1 :(得分:0)

由于@bhmahler的建议,这是解决此问题的解决方案

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 line needs to be added before creating ObservableCollection
        children.OrderBy(item_level2 => item_level2.Contents[1].Content).ToList();
        this.Children = new ObservableCollection<BranchLevel_2>(children);
    }
}