【转】C# 中Linq查询所有上级节点或所有下级节点
生活随笔
收集整理的這篇文章主要介紹了
【转】C# 中Linq查询所有上级节点或所有下级节点
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;namespace ConsoleApp7
{class Program{static void Main(string[] args){var data = GetData();//獲取所有下級//var query = GetSons(data, 1);//獲取所有上級var query = GetFatherList(data, 5);Console.WriteLine("Id\t 區劃\t 父ID\t 層級\t");query.ToList().ForEach(q => Console.WriteLine("{0}\t {1}\t {2}\t {3}\t", q.Id, q.Name, q.Fid, q.Level));Console.ReadLine();}#region 測試數據public static IList<menu> GetData(){var list = new List<menu>();list.Add(new menu { Id = 1, Name = "廣東省", Fid = 0, Level = 1 });list.Add(new menu { Id = 2, Name = "深圳市", Fid = 1, Level = 2 });list.Add(new menu { Id = 3, Name = "南山區", Fid = 2, Level = 3 });list.Add(new menu { Id = 4, Name = "福田區", Fid = 2, Level = 3 });list.Add(new menu { Id = 5, Name = "上梅林", Fid = 4, Level = 4 });list.Add(new menu { Id = 6, Name = "下梅林", Fid = 4, Level = 4 });list.Add(new menu { Id = 7, Name = "車公廟", Fid = 4, Level = 4 });list.Add(new menu { Id = 8, Name = "蛇口", Fid = 5, Level = 4 });list.Add(new menu { Id = 9, Name = "科技園", Fid = 5, Level = 4 });list.Add(new menu { Id = 10, Name = "湖南省", Fid = 0, Level = 1 });list.Add(new menu { Id = 11, Name = "長沙市", Fid = 10, Level = 2 });list.Add(new menu { Id = 12, Name = "芙蓉區", Fid = 11, Level = 3 });return list;}#endregion#region 獲取所有下級public static IEnumerable<menu> GetSons(IList<menu> list, int Fid){var query = list.Where(p => p.Id == Fid).ToList();var list2 = query.Concat(GetSonList(list, Fid));return list2;}public static IEnumerable<menu> GetSonList(IList<menu> list, int Fid){var query = list.Where(p => p.Fid == Fid).ToList();return query.ToList().Concat(query.ToList().SelectMany(t => GetSonList(list, t.Id)));}#endregion#region 獲取所有上級public static IEnumerable<menu> GetFatherList(IList<menu> list, int Id){var query = list.Where(p => p.Id == Id).ToList();return query.ToList().Concat(query.ToList().SelectMany(t => GetFatherList(list, t.Fid)));}#endregion#region 實體類public class menu{public int Id { set; get; }public string Name { set; get; }public int Fid { set; get; }public int Level { set; get; }}#endregion}
}
?轉自:https://blog.csdn.net/smartsmile2012/article/details/81317327
轉載于:https://www.cnblogs.com/yunspider/p/10502225.html
總結
以上是生活随笔為你收集整理的【转】C# 中Linq查询所有上级节点或所有下级节点的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: P4245 【模板】任意模数NTT
- 下一篇: webpack简单配置