none
如何用Linq搜尋出不同層級的節點? RRS feed

  • 問題

  • 各位好,想請教一下各位前輩

    我有一個表示階層的物件資料清單,以JSON格式來表示如下:
    [
        {
            "Id": "100",
            "Name": "A",
            "Level": "1",
            "Child": [
                {
                    "Id": "201",
                    "Name": "A1",
                    "Level": "2",
                    "Child": [
                        {
                            "Id": "301",
                            "Name": "A3",
                            "Level": "3"
                        },
                        {
                            "Id": "302",
                            "Name": "A31",
                            "Level": "3"
                        }
                    ]
                },
                {
                    "Id": "202",
                    "Name": "A2",
                    "Level": "2",
                    "Child": null
                }
            ]
        },
        {
            "Id": "101",
            "Name": "B",
            "Level": "1",
            "Child": null
        },
        {
            "Id": "102",
            "Name": "C",
            "Level": "1",
            "Child": [
                {
                    "Id": "203",
                    "Name": "C2",
                    "Level": "2",
                    "Child": [
                        {
                            "Id": "303",
                            "Name": "C3",
                            "Level": "3",
                            "Child": null
                        }
                    ]
                }
            ]
        }
    ]

    我的問題是,要如何用Linq來搜尋出所有Level = 3的節點資料呢?

    我目前的做法是用2個foreach來做

    但覺得似乎可以有更簡潔的寫法才對

    請各位前輩不吝指教

    謝謝

    2015年10月28日 下午 03:23

解答

  • 有點難單用linq去實作出來,就算做出來也沒法簡潔到哪裡去。

    因為你知道你只有三層,像這種有階層性的,我都建議用遞迴。

    =================================================

    這篇給你參考 linq + 遞迴

    http://www.superstarcoders.com/blogs/posts/recursive-select-in-c-sharp-and-linq.aspx

                Console.WriteLine("取得全部的node");
                foreach (var i in source.RecursiveSelect(p => p.Child))
                {
                    Console.WriteLine(i.Id + "\t" + i.Name + "\t" + i.Level);
                }
    
                Console.WriteLine("取得level為3的node");
                foreach (var i in source.RecursiveSelect(p => p.Child).Where(q => q.Level == 3))
                {
                    Console.WriteLine(i.Id + "\t" + i.Name + "\t" + i.Level);
                }

    結果

    2015年10月28日 下午 05:20