Given this class:
public class Parent
{
开发者_运维百科 public Child[] Children {get;set;}
}
And this array:
Parent[] parents;
How can I retrieve all the children from the parents array using Linq or something else? This seems bad:
IList<Child> children = new List<Child>();
foreach(var parent in parents)
children.AddRange(parent.Children);
Or is that not so bad? :-)
Try this:
parents.SelectMany(p => p.Children).ToArray()
I don't think the solution you propose in the question is bad. It is very readable and easy to understand what is going on. Unless you have some reason you need to optimize this, I don't see any fault with it.
If you just really want to use Linq, that's another story (and in my opinion perfectly valid -- the more experience/practice with Linq, the better)
精彩评论