簡體   English   中英

如何將 obj 移動到 c# 中的列表頂部

[英]how to move obj to the top of list in c#

我想將obj.Coach.Id=xxx的一些 object 移到List<obj>的頂部,這是我的解決方案,但我認為它不是最優的,因為它會遍歷兩次。 有什么好的方法可以實現嗎?


    List<AppointmentDTO> res = await this.appointmentService.GetCanReserve(coachId, date);

    var id =  HttpContext.User.FindFirst("id")?.Value;
    if (id is not null)
    {
        var temp= res.Where(r => r.Coach.Id == id).ToList();

        res = res.Where(r => r.Coach.Id != id).ToList();

        res.InsertRange(0,temp);
    }

您可以使用 OrderBy 和 ThenBy 對結果進行排序。 IE:

var ordered = res.OrderBy(r => r.Coach_id == id?0:1)
                 .ThenBy(r => r.Coach_id)
                 .ToList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM