简体   繁体   English

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

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

I had a problem to order sub-elements in List and found the topic to discuss List<T> vs IEnumerable<T> in foreach .I wonder how to order child List by using LINQ or Lambda Expression.我在对 List 中的子元素进行排序时遇到了问题,并找到了在 foreach 中讨论List<T> 与 IEnumerable<T>的主题。我想知道如何使用 LINQ 或 Lambda 表达式对子 List 进行排序。 Can someone recommend me?有人可以推荐我吗? the code example as follows:代码示例如下:

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.
}

You enumerate result each time that you enumerate the return IEnumerable of DoStuff , plus one additional time inside the loop in DoStuff itself.每次枚举DoStuff的返回IEnumerable时都会枚举result ,再加上DoStuff本身的循环内的额外时间。 Modifications you make inside the loop do not stay, though, because of deferred execution : next time you enumerate DoStuff() there is another call to DoOtherStuff etc.但是,由于延迟执行,您在循环内所做的修改不会保留:下次您枚举DoStuff() ,会再次调用DoOtherStuff等。

You can fix this in several ways:您可以通过多种方式解决此问题:

  • Convert result to list before sorting children, ie在排序孩子之前将result转换为列表,即

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

     DoOtherStuff() // Returns IEnumerable<Parent> .Select(parent => { parent.Children = parent.Children.OrderBy(YetAnotherPredicate).ToList(); return parent; }) .OrderByDescending(SomePredicate) .ThenBy(AnotherPredicate) .ToList();
  • Use yield return result in the loop (this is a variation of the Select solution).在循环中使用yield return result (这是Select解决方案的变体)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM