LINQ递归函数? [英] LINQ recursion function?
问题描述
让我们以这个n层深层结构为例:
public class SomeItem
{
public Guid ID {get; set; }
public string Name {get;组; }
public bool HasChildren {get; set; }
public IEnumerable< SomeItem>儿童{get;组; }
}
如果我正在寻找一个特定的项目结构)是有一些LINQ的好处,我可以使用它轻松地在单个语句中获取它,或者我必须使用一些递归函数如下:
private SomeItem GetSomeItem(IEnumerable< SomeItem> items,Guid ID)
{
foreach(var item in items)
{
if(item.ID == ID )
{
return item;
}
else if(item.HasChildren)
{
return GetSomeItem(item.Children,ID);
}
}
return null; LINQ并不是真正的真正的,因为它不是真正的 do递归。你的解决方案似乎是合适的 - 虽然我不知道HasChildren是真的需要...为什么不使用空列表的项目没有孩子?
写一个 DescendantsAndSelf
方法,该方法将返回所有后代(包括项目本身)的全部,类似这样的东西;
//警告:可能贵!
public IEnumerable< SomeItem> DescendantsAndSelf()
{
yield return this;
foreach(Children.SelectMany(x => x.DescendantsAndSelf())中的var项)
{
yield return item;
}
}
然而,如果树很深,非常低效,因为每个项目需要通过其祖先的所有迭代器。 Wes Dyer有关于此的博文,显示更有效的实施。
无论如何,如果你有一个这样的方法(但是实现),你可以使用正常的where子句来找到一个项目(或First / FirstOrDefault等) )。
Let's take this n-tier deep structure for example:
public class SomeItem
{
public Guid ID { get;set; }
public string Name { get; set; }
public bool HasChildren { get;set; }
public IEnumerable<SomeItem> Children { get; set; }
}
If I am looking to get a particular Item by ID (anywhere in the structure) is there some LINQ goodness I can use to easily get it in a single statement or do I have to use some recursive function as below:
private SomeItem GetSomeItem(IEnumerable<SomeItem> items, Guid ID)
{
foreach (var item in items)
{
if (item.ID == ID)
{
return item;
}
else if (item.HasChildren)
{
return GetSomeItem(item.Children, ID);
}
}
return null;
}
解决方案 LINQ doesn't really "do" recursion nicely. Your solution seems appropriate - although I'm not sure HasChildren is really required... why not just use an empty list for an item with no children?
An alternative is to write a DescendantsAndSelf
method which will return all of the descendants (including the item itself), something like this;
// Warning: potentially expensive!
public IEnumerable<SomeItem> DescendantsAndSelf()
{
yield return this;
foreach (var item in Children.SelectMany(x => x.DescendantsAndSelf()))
{
yield return item;
}
}
However, if the tree is deep that ends up being very inefficient because each item needs to "pass through" all the iterators of its ancestry. Wes Dyer has blogged about this, showing a more efficient implementation.
Anyway, if you have a method like this (however it's implemented) you can just use a normal "where" clause to find an item (or First/FirstOrDefault etc).
这篇关于LINQ递归函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!