欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Linq实现SQL中的递归查询

程序员文章站 2022-03-29 20:24:00
废话不多说,直接上代码:using System;using System.Collections.Generic;using System.ComponentModel.Design;using System.Data;using System.Data.SqlClient;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApp1{ class Program...

废话不多说,直接上代码:

using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Region> list = GetTestData();
            List<Region> query = GetResult(list, 2);
            foreach (Region region in query)
            {
                Console.WriteLine(region.Name);
            }
            Console.ReadKey();
        }

        // 测试数据
        static List<Region> GetTestData()
        {
            List<Region> list = new List<Region>();
            list.Add(new Region() { Id = 1, ParentId = 0, Name = "中国" });
            list.Add(new Region() { Id = 2, ParentId = 1, Name = "浙江" });
            list.Add(new Region() { Id = 3, ParentId = 1, Name = "江苏" });
            list.Add(new Region() { Id = 4, ParentId = 2, Name = "杭州" });
            list.Add(new Region() { Id = 5, ParentId = 2, Name = "宁波" });
            list.Add(new Region() { Id = 6, ParentId = 3, Name = "南京" });
            list.Add(new Region() { Id = 7, ParentId = 3, Name = "苏州" });
            return list;
        }

        // 递归查询
        static IEnumerable<Region> GetRegion(List<Region> list, int id)
        {
            IEnumerable<Region> query = from region in list
                                        where region.ParentId == id
                                        select region;
            return query.ToList().Concat(query.ToList().SelectMany(r => GetRegion(list, r.Id)));
        }

        // 生成最终结果
        static List<Region> GetResult(List<Region> list, int id)
        {
            List<Region> regions = new List<Region>();
            regions.AddRange(list.Where(r => r.Id == id));
            regions.AddRange(GetRegion(list, id));
            return regions;
        }
    }
}

运行结果如下:

浙江
杭州
宁波

本文地址:https://blog.csdn.net/HerryDong/article/details/107407721

相关标签: C# Linq