Is there a linq-y way to combine the properties of a collection of an object collection?

Sorry, this title just hurts. I am wondering if there is a Linq to collections extension method that collapses the following code segment into one line:

public IEnumerable<Child> GetAllChildren(IEnumerable<Parent> parents){

  var result = new List<Child>();

  foreach(Parent parent in parents)
    foreach(Child child in parent.Children)
      result.Add(child);

  return result;
}

If you can collapse this into a single statement, try it with insane complexity:

public IEnumerable<Child> GetAllChildren(IEnumerable<Grandparent> nanas){

  var result = new List<Child>();

  foreach(Grandparent papa in nanas)
    foreach(Parent parent in papa.Children)
      foreach(Child child in parent.Children)
        result.Add(child);

  return result;
}
+3
source share
2 answers

Here is the form of the required method.

return parents
  .SelectMany(p => p.Children);

And for two levels:

return oldies
  .SelectMany(grand => grand.Children)
  .SelectMany(parent => parent.Children);
+7
source

This will work:

public IEnumerable<Child> GetAllChildren(IEnumerable<Parent> parents)
{
    return from parent in parents
           from child in parent.Children
           select child;
}

and then this:

public IEnumerable<Child> GetAllChildren(IEnumerable<Grandparent> nanas)
{
    return from papa in nanas
           from parent in papa.Children
           from child in parent.Children
           select child;
}

Please note that in this example I am not actually returning a list, I am returning an IEnumerable data source which, until you start using it or the like, will not actually process it.

If you need to return a list, modify each return statement as follows:

    return (from .....
            ...
            select child).ToList();
+9
source

Source: https://habr.com/ru/post/1698302/


All Articles