按嵌套列表C#上的属性排序

时间:2018-08-30 18:49:30

标签: c# linq sorting

我有一个列表,希望按嵌套列表内的属性进行排序。如果该属性值存在于其中一个对象中,则希望它在列表中排在第一位。否则,如果该属性不存在,请按父对象中的属性对其进行排序。

代码:

这是顶级班级;

我想按特定的 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" }

1 个答案:

答案 0 :(得分:2)

怎么样

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

最初发出的命令是先放置标签= 22的笔记,然后按noteId排序