c# - 使用 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();
有什么提示吗?
解决方案
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));
}
}
}
推荐阅读
- python - 根据两列值将单行转换为两行
- ios13 - 如何在 Xcode 11 中为 iOS 12 编写应用程序?
- caching - WSO2:缓存键和响应
- python - 使用 python 3.6 的 Anaconda 环境无法正常工作
- swift - 在 UICollectionViewCompositionalLayout / UICollectionViewDiffableDataSource 的两个不同部分显示同一个对象
- android - 我正在尝试在手机上打开 Expo 项目,但出现错误
- testing - Flutter Mockito 验证是否调用了传递给小部件的回调
- javascript - 如何在 Vuejs 中使用计算来观察深度数组
- javascript - 如何在 JavaScript 中仅使用一个计算出的数字创建图表/绘图?
- javascript - 使用更改一个单元格时更新谷歌表格中的一系列单元格