开发者

Retrieve All Children From Parent[]

开发者 https://www.devze.com 2023-01-10 18:48 出处:网络
Given this class: public class Parent { 开发者_运维百科 public Child[] Children {get;set;} } And this array:

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)

0

精彩评论

暂无评论...
验证码 换一张
取 消