c# - 按嵌套列表c#上的属性排序
问题描述
我有一个列表,我想按嵌套列表中的属性进行排序。如果属性值存在于其中一个对象中,我希望它位于列表的第一位。否则,如果该属性不存在,则按父对象中的某个属性对其进行排序。
代码:
这是顶级课程;
我想按特定的TagId排序。然后按NoteId升序排列。
public class NoteDto
{
string NoteText { get; set; }
public int NoteId { get; set; }
public List<TagDto> Tags { get; set; }
}
嵌套对象类:
public class TagDto
{
public int TagId { get; set; }
public string Name { get; set; }
}
示例:如果TagId为 22,我希望它在列表中排在第一位,否则按升序按NoteId排序。
排序前
NoteText: "TestNote1",
NoteId: 1,
Tags: { TagId: 13, Name: "TestTag1" }, { TagId: 16, Name: "TestTag5" }
NoteText: "TestNote2",
NoteId: 2,
Tags: { TagId: 14, Name: "TestTag2" }, { TagId: 17, Name: "TestTag6" }
NoteText: "TestNote3",
NoteId: 3,
Tags: { TagId: 15, Name: "TestTag3" }, { TagId: 18, Name: "TestTag7" }
NoteText: "TestNote4",
NoteId: 4,
Tags: { TagId: 22, Name: "TestTag4" }, { TagId: 19, Name: "TestTag8" }
排序后:
NoteText: "TestNote4",
NoteId: 4,
Tags: { TagId: 22, Name: "TestTag4" }, { TagId: 19, Name: "TestTag8" }
NoteText: "TestNote1",
NoteId: 1,
Tags: { TagId: 13, Name: "TestTag1" }, { TagId: 16, Name: "TestTag5" }
NoteText: "TestNote2",
NoteId: 2,
Tags: { TagId: 14, Name: "TestTag2" }, { TagId: 17, Name: "TestTag6" }
NoteText: "TestNote3",
NoteId: 3,
Tags: { TagId: 15, Name: "TestTag3" }, { TagId: 18, Name: "TestTag7" }
解决方案
这个怎么样
var sorted = notes.OrderByDescending(note => note.Tags.Any(t => t.TagId == 22))
.ThenBy(note => note.noteId);
初始命令首先放置标签 = 22 的注释,然后按 noteId 排序
推荐阅读
- php - PHP 正则表达式获取所有作为 HTML 元素属性值的电子邮件地址,例如“
我有这个正则表达式模式
/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i
,用于从字符串中获取电子邮件地址。但现在我只想获取所有电子邮件地址,它们是任意 HTML 元素属性的值,包括属性本身。看看我的例子,一切都应该清楚:<?
- laravel - 在开发机器上运行的 Laravel 项目在 Windows 更新后出现“此站点不安全错误”后出现此错误
- python - 重新采样(非采样)在 Pandas 数据帧上产生不可预测的错误
- r - 通过索引从另一个向量返回 ifelse 的值
- visual-studio-2015 - 无法使用通用身份验证连接到设备“192.168.1.17”
- jquery - 如何使用 django 和 ajax 创建 3 个依赖下拉列表
- javascript - 如何为多个值使用 javascript 地图功能
- javascript - 价格jquery中的小数位自动格式
- reactjs - 我可以在另一个 React-Router 应用程序中嵌入或提供构建的 React 应用程序吗?
- google-apps-script - Google Apps Script SpreadsheetApp Banding Class - 如何访问这些方法