首页 > 代码库 > LINQ TO SQL 实现无限递归查询
LINQ TO SQL 实现无限递归查询
LINQ TO SQL 实现无限递归查询
现总结一下,希望能给以后再碰到此类问题的朋友一些帮助
--构造测试数据: 只作演示用CREATE TABLE [dbo].[Tim_LinqTable]([Id] int PRIMARY KEY IDENTITY(1,1) NOT NULL,[Name] [varchar](50) NOT NULL,[Parent] int NOT NULL,)GO INSERT INTO [Tim_LinqTable] SELECT ‘A‘,0 UNION ALLSELECT ‘A1‘,1 UNION ALLSELECT ‘A2‘,1 UNION ALLSELECT ‘B1‘,2 UNION ALLSELECT ‘B2‘,3 UNION ALLSELECT ‘C1‘,4 UNION ALLSELECT ‘C2‘,4 UNION ALLSELECT ‘D1‘,5 UNION ALLSELECT ‘D2‘,5 UNION ALLSELECT ‘D3‘,5 GO WITH tempAS(SELECT * FROM [Tim_LinqTable] WHERE Parent = 3UNION ALLSELECT m.* FROM [Tim_LinqTable] AS mINNER JOIN temp AS child ON m.Parent = child.Id)SELECT * FROM tempGO --查询 Parent=3 的所有子数据结果如下:Id Name Parent----------- -------------------------------------------------- -----------5 B2 38 D1 59 D2 510 D3 5 (4 row(s) affected)
//好,下边来看看用C#怎么实现上边的SQL语句吧:void Main(){ var query=GetClassID(3); Console.WriteLine("Id\tName\tParent"); query.ToList().ForEach(q=>Console.WriteLine("{0}\t{1}\t{2}",q.Id,q.Name,q.Parent)); /* Id Name Parent 5 B2 3 8 D1 5 9 D2 5 10 D3 5 */}public IEnumerable<Tim_LinqTable> GetClassID(int p_id){ var query = from c in this.Tim_LinqTables where c.Parent == p_id select c; return query.ToList().Concat(query.ToList().SelectMany(t => GetClassID(t.Id))); }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。