专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > LINQ

LINQ 递归 关注, 网上找不到材料. 用一条LINQ 递归.求大侠.解决办法

发布时间:2011-06-24 21:48:15 文章来源:www.iduyao.cn 采编人员:星星草
LINQ 递归 关注,,,, 网上找不到材料...... 用一条LINQ 递归......求大侠.....
用一条LINQ 递归......求大侠

最简单的一种,希望大侠能给我点提示/........


id subid
1 2
2 3
3 4
a b
b 5
a 6
c 7
: :
: :
: :



给出.id = 3  

递归求出. 相关连的 id  
为 1,2,3 


关注....


------解决方案--------------------
也许不用LINQ更好吧,但如果你坚持的话,大概这样吧

using System;
using System.Collections.Generic;
using System.Linq;

class Node
{
public string ID { get;set;}
public string ParentID { get;set;}
}

static class NodeExtension
{
public static IEnumerable<Node> GetAncestors(this IEnumerable<Node> nodes, string parentID)
{
var parentNodes = from node in nodes 
where node.ID == parentID 
select node;

foreach(var node in parentNodes)
{
yield return node;
}

foreach(var node in parentNodes)
{
foreach(var p in nodes.GetAncestors(node.ParentID))
yield return p;
}


}
}

class TestID
{
static void Main()
{
List<Node> nodes = new List<Node>
{
new Node {ID = "1", ParentID=null},
new Node {ID = "2", ParentID="1"},
new Node {ID = "3", ParentID="2"},
new Node {ID = "4", ParentID="3"},
new Node {ID = "5", ParentID="4"},
new Node {ID = "a", ParentID="5"},
new Node {ID = "b", ParentID="a"}
};

var ancensters = nodes.GetAncestors("3");

foreach(var node in ancensters)
Console.WriteLine("{0}={1}",node.ID,node.ParentID);

 }
}
------解决方案--------------------
LS的做法其实与LINQ无关。


这种问题当然最好的办法就是递归,树形结构本来就是递归所解决的问题。

SQL是面向集合的而不是面向树的查询语言,LINQ不过是把SQL语法写到程序中。很明显,SQL本来就没法解决树的问题,难道说写到程序中就能解决了?
------解决方案--------------------
实际上,你写一个返回IQueryable<T>的函数(很简单,只有两三条语句)然后在表达式中调用这个函数就能递归了。
------解决方案--------------------
Func<int, int> factorial =
 Extensions.YCombinator<int, int>(
fact =>
n => n < 2 ? 1 : n * fact(n - 1));
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: