首页 > 解决方案 > 按嵌套列表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" }

标签: c#linqsorting

解决方案


这个怎么样

var sorted = notes.OrderByDescending(note => note.Tags.Any(t => t.TagId == 22))
                     .ThenBy(note => note.noteId);

初始命令首先放置标签 = 22 的注释,然后按 noteId 排序


推荐阅读