簡體   English   中英

使用 LINQ 或 Lambda 表達式按降序排列子元素

[英]To Order By Descending sub-elements using LINQ or Lambda Expression

我在對 List 中的子元素進行排序時遇到了問題,並找到了在 foreach 中討論List<T> 與 IEnumerable<T>的主題。我想知道如何使用 LINQ 或 Lambda 表達式對子 List 進行排序。 有人可以推薦我嗎? 代碼示例如下:

public class Parent
{
    // Other properties...
    public IList<Child> Children { get; set; }
}

public IEnumerable<Parent> DoStuff()
{
    var result = DoOtherStuff() // Returns IEnumerable<Parent>
        .OrderByDescending(SomePredicate) 
        .ThenBy(AnotherPredicate); // This sorting works as expected in the return value.

    foreach (Parent parent in result)
    {
        parent.Children = parent.Children.OrderBy(YetAnotherPredicate).ToList();
        // When I look at parent.Children here in the debugger, it's sorted properly.
    }

    return result;
    // When I look at the return value, the Children are not sorted.
}

每次枚舉DoStuff的返回IEnumerable時都會枚舉result ,再加上DoStuff本身的循環內的額外時間。 但是,由於延遲執行,您在循環內所做的修改不會保留:下次您枚舉DoStuff() ,會再次調用DoOtherStuff等。

您可以通過多種方式解決此問題:

  • 在排序孩子之前將result轉換為列表,即

    DoOtherStuff() // Returns IEnumerable<Parent> .OrderByDescending(SomePredicate) .ThenBy(AnotherPredicate) .ToList();
  • Select添加子排序:

     DoOtherStuff() // Returns IEnumerable<Parent> .Select(parent => { parent.Children = parent.Children.OrderBy(YetAnotherPredicate).ToList(); return parent; }) .OrderByDescending(SomePredicate) .ThenBy(AnotherPredicate) .ToList();
  • 在循環中使用yield return result (這是Select解決方案的變體)。

暫無
暫無

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

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