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. 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. 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.
You can fix this in several ways:
Convert result
to list before sorting children, ie
DoOtherStuff() // Returns IEnumerable<Parent> .OrderByDescending(SomePredicate) .ThenBy(AnotherPredicate) .ToList();
Add child sorting in a 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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.