├── .github └── workflows │ └── dotnet.yml ├── .gitignore ├── CHANGELOG.txt ├── FluentSimpleTree.sln ├── LICENSE.txt ├── README.md └── src └── FluentSimpleTree ├── FluentSimpleTree.csproj ├── IGenericTreeNode.cs ├── Tree.cs └── icon.png /.github/workflows/dotnet.yml: -------------------------------------------------------------------------------- 1 | name: Build Solution 2 | on: 3 | push: 4 | tags: 5 | - "[0-9]+.[0-9]+.[0-9]+" 6 | workflow_dispatch: 7 | inputs: 8 | name: 9 | description: 'Manual trigger' 10 | required: true 11 | default: 'Manual trigger' 12 | jobs: 13 | build: 14 | name: Build 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v3 18 | 19 | - name: Setup .NET 20 | uses: actions/setup-dotnet@v3 21 | with: 22 | dotnet-version: 3.1.417 23 | 24 | - name: Restore dependencies 25 | run: dotnet restore 26 | 27 | - name: Build 28 | run: dotnet build --no-restore 29 | 30 | publish: 31 | runs-on: windows-latest 32 | 33 | steps: 34 | - name: Checkout 35 | uses: actions/checkout@v3 36 | 37 | - name: Verify commit exists in origin/main 38 | run: | 39 | git fetch --no-tags --prune --depth=1 origin +refs/heads/*:refs/remotes/origin/* 40 | git branch --remote --contains | grep origin/main 41 | 42 | - name: Build 43 | run: dotnet build -c Release 44 | 45 | - name: Pack 46 | run: dotnet pack -c Release -o . --no-build 47 | 48 | - name: Push 49 | run: dotnet nuget push *.nupkg -s https://api.nuget.org/v3/index.json -k ${{ secrets.NUGET_KEY }} 50 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # Tye 66 | .tye/ 67 | 68 | # ASP.NET Scaffolding 69 | ScaffoldingReadMe.txt 70 | 71 | # StyleCop 72 | StyleCopReport.xml 73 | 74 | # Files built by Visual Studio 75 | *_i.c 76 | *_p.c 77 | *_h.h 78 | *.ilk 79 | *.meta 80 | *.obj 81 | *.iobj 82 | *.pch 83 | *.pdb 84 | *.ipdb 85 | *.pgc 86 | *.pgd 87 | *.rsp 88 | *.sbr 89 | *.tlb 90 | *.tli 91 | *.tlh 92 | *.tmp 93 | *.tmp_proj 94 | *_wpftmp.csproj 95 | *.log 96 | *.vspscc 97 | *.vssscc 98 | .builds 99 | *.pidb 100 | *.svclog 101 | *.scc 102 | 103 | # Chutzpah Test files 104 | _Chutzpah* 105 | 106 | # Visual C++ cache files 107 | ipch/ 108 | *.aps 109 | *.ncb 110 | *.opendb 111 | *.opensdf 112 | *.sdf 113 | *.cachefile 114 | *.VC.db 115 | *.VC.VC.opendb 116 | 117 | # Visual Studio profiler 118 | *.psess 119 | *.vsp 120 | *.vspx 121 | *.sap 122 | 123 | # Visual Studio Trace Files 124 | *.e2e 125 | 126 | # TFS 2012 Local Workspace 127 | $tf/ 128 | 129 | # Guidance Automation Toolkit 130 | *.gpState 131 | 132 | # ReSharper is a .NET coding add-in 133 | _ReSharper*/ 134 | *.[Rr]e[Ss]harper 135 | *.DotSettings.user 136 | 137 | # TeamCity is a build add-in 138 | _TeamCity* 139 | 140 | # DotCover is a Code Coverage Tool 141 | *.dotCover 142 | 143 | # AxoCover is a Code Coverage Tool 144 | .axoCover/* 145 | !.axoCover/settings.json 146 | 147 | # Coverlet is a free, cross platform Code Coverage Tool 148 | coverage*.json 149 | coverage*.xml 150 | coverage*.info 151 | 152 | # Visual Studio code coverage results 153 | *.coverage 154 | *.coveragexml 155 | 156 | # NCrunch 157 | _NCrunch_* 158 | .*crunch*.local.xml 159 | nCrunchTemp_* 160 | 161 | # MightyMoose 162 | *.mm.* 163 | AutoTest.Net/ 164 | 165 | # Web workbench (sass) 166 | .sass-cache/ 167 | 168 | # Installshield output folder 169 | [Ee]xpress/ 170 | 171 | # DocProject is a documentation generator add-in 172 | DocProject/buildhelp/ 173 | DocProject/Help/*.HxT 174 | DocProject/Help/*.HxC 175 | DocProject/Help/*.hhc 176 | DocProject/Help/*.hhk 177 | DocProject/Help/*.hhp 178 | DocProject/Help/Html2 179 | DocProject/Help/html 180 | 181 | # Click-Once directory 182 | publish/ 183 | 184 | # Publish Web Output 185 | *.[Pp]ublish.xml 186 | *.azurePubxml 187 | # Note: Comment the next line if you want to checkin your web deploy settings, 188 | # but database connection strings (with potential passwords) will be unencrypted 189 | *.pubxml 190 | *.publishproj 191 | 192 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 193 | # checkin your Azure Web App publish settings, but sensitive information contained 194 | # in these scripts will be unencrypted 195 | PublishScripts/ 196 | 197 | # NuGet Packages 198 | *.nupkg 199 | # NuGet Symbol Packages 200 | *.snupkg 201 | # The packages folder can be ignored because of Package Restore 202 | **/[Pp]ackages/* 203 | # except build/, which is used as an MSBuild target. 204 | !**/[Pp]ackages/build/ 205 | # Uncomment if necessary however generally it will be regenerated when needed 206 | #!**/[Pp]ackages/repositories.config 207 | # NuGet v3's project.json files produces more ignorable files 208 | *.nuget.props 209 | *.nuget.targets 210 | 211 | # Microsoft Azure Build Output 212 | csx/ 213 | *.build.csdef 214 | 215 | # Microsoft Azure Emulator 216 | ecf/ 217 | rcf/ 218 | 219 | # Windows Store app package directories and files 220 | AppPackages/ 221 | BundleArtifacts/ 222 | Package.StoreAssociation.xml 223 | _pkginfo.txt 224 | *.appx 225 | *.appxbundle 226 | *.appxupload 227 | 228 | # Visual Studio cache files 229 | # files ending in .cache can be ignored 230 | *.[Cc]ache 231 | # but keep track of directories ending in .cache 232 | !?*.[Cc]ache/ 233 | 234 | # Others 235 | ClientBin/ 236 | ~$* 237 | *~ 238 | *.dbmdl 239 | *.dbproj.schemaview 240 | *.jfm 241 | *.pfx 242 | *.publishsettings 243 | orleans.codegen.cs 244 | 245 | # Including strong name files can present a security risk 246 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 247 | #*.snk 248 | 249 | # Since there are multiple workflows, uncomment next line to ignore bower_components 250 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 251 | #bower_components/ 252 | 253 | # RIA/Silverlight projects 254 | Generated_Code/ 255 | 256 | # Backup & report files from converting an old project file 257 | # to a newer Visual Studio version. Backup files are not needed, 258 | # because we have git ;-) 259 | _UpgradeReport_Files/ 260 | Backup*/ 261 | UpgradeLog*.XML 262 | UpgradeLog*.htm 263 | ServiceFabricBackup/ 264 | *.rptproj.bak 265 | 266 | # SQL Server files 267 | *.mdf 268 | *.ldf 269 | *.ndf 270 | 271 | # Business Intelligence projects 272 | *.rdl.data 273 | *.bim.layout 274 | *.bim_*.settings 275 | *.rptproj.rsuser 276 | *- [Bb]ackup.rdl 277 | *- [Bb]ackup ([0-9]).rdl 278 | *- [Bb]ackup ([0-9][0-9]).rdl 279 | 280 | # Microsoft Fakes 281 | FakesAssemblies/ 282 | 283 | # GhostDoc plugin setting file 284 | *.GhostDoc.xml 285 | 286 | # Node.js Tools for Visual Studio 287 | .ntvs_analysis.dat 288 | node_modules/ 289 | 290 | # Visual Studio 6 build log 291 | *.plg 292 | 293 | # Visual Studio 6 workspace options file 294 | *.opt 295 | 296 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 297 | *.vbw 298 | 299 | # Visual Studio LightSwitch build output 300 | **/*.HTMLClient/GeneratedArtifacts 301 | **/*.DesktopClient/GeneratedArtifacts 302 | **/*.DesktopClient/ModelManifest.xml 303 | **/*.Server/GeneratedArtifacts 304 | **/*.Server/ModelManifest.xml 305 | _Pvt_Extensions 306 | 307 | # Paket dependency manager 308 | .paket/paket.exe 309 | paket-files/ 310 | 311 | # FAKE - F# Make 312 | .fake/ 313 | 314 | # CodeRush personal settings 315 | .cr/personal 316 | 317 | # Python Tools for Visual Studio (PTVS) 318 | __pycache__/ 319 | *.pyc 320 | 321 | # Cake - Uncomment if you are using it 322 | # tools/** 323 | # !tools/packages.config 324 | 325 | # Tabs Studio 326 | *.tss 327 | 328 | # Telerik's JustMock configuration file 329 | *.jmconfig 330 | 331 | # BizTalk build output 332 | *.btp.cs 333 | *.btm.cs 334 | *.odx.cs 335 | *.xsd.cs 336 | 337 | # OpenCover UI analysis results 338 | OpenCover/ 339 | 340 | # Azure Stream Analytics local run output 341 | ASALocalRun/ 342 | 343 | # MSBuild Binary and Structured Log 344 | *.binlog 345 | 346 | # NVidia Nsight GPU debugger configuration file 347 | *.nvuser 348 | 349 | # MFractors (Xamarin productivity tool) working folder 350 | .mfractor/ 351 | 352 | # Local History for Visual Studio 353 | .localhistory/ 354 | 355 | # BeatPulse healthcheck temp database 356 | healthchecksdb 357 | 358 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 359 | MigrationBackup/ 360 | 361 | # Ionide (cross platform F# VS Code tools) working folder 362 | .ionide/ 363 | 364 | # Fody - auto-generated XML schema 365 | FodyWeavers.xsd 366 | 367 | ## 368 | ## Visual studio for Mac 369 | ## 370 | 371 | 372 | # globs 373 | Makefile.in 374 | *.userprefs 375 | *.usertasks 376 | config.make 377 | config.status 378 | aclocal.m4 379 | install-sh 380 | autom4te.cache/ 381 | *.tar.gz 382 | tarballs/ 383 | test-results/ 384 | 385 | # Mac bundle stuff 386 | *.dmg 387 | *.app 388 | 389 | # content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore 390 | # General 391 | .DS_Store 392 | .AppleDouble 393 | .LSOverride 394 | 395 | # Icon must end with two \r 396 | Icon 397 | 398 | 399 | # Thumbnails 400 | ._* 401 | 402 | # Files that might appear in the root of a volume 403 | .DocumentRevisions-V100 404 | .fseventsd 405 | .Spotlight-V100 406 | .TemporaryItems 407 | .Trashes 408 | .VolumeIcon.icns 409 | .com.apple.timemachine.donotpresent 410 | 411 | # Directories potentially created on remote AFP share 412 | .AppleDB 413 | .AppleDesktop 414 | Network Trash Folder 415 | Temporary Items 416 | .apdisk 417 | 418 | # content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore 419 | # Windows thumbnail cache files 420 | Thumbs.db 421 | ehthumbs.db 422 | ehthumbs_vista.db 423 | 424 | # Dump file 425 | *.stackdump 426 | 427 | # Folder config file 428 | [Dd]esktop.ini 429 | 430 | # Recycle Bin used on file shares 431 | $RECYCLE.BIN/ 432 | 433 | # Windows Installer files 434 | *.cab 435 | *.msi 436 | *.msix 437 | *.msm 438 | *.msp 439 | 440 | # Windows shortcuts 441 | *.lnk 442 | 443 | # JetBrains Rider 444 | .idea/ 445 | *.sln.iml 446 | 447 | ## 448 | ## Visual Studio Code 449 | ## 450 | .vscode/* 451 | !.vscode/settings.json 452 | !.vscode/tasks.json 453 | !.vscode/launch.json 454 | !.vscode/extensions.json 455 | -------------------------------------------------------------------------------- /CHANGELOG.txt: -------------------------------------------------------------------------------- 1 | 1.0.3 2 | Added 3 | - IGenericTreeNode.Remove() to allow removal of the node itself from the tree, à la JavaScript with DOM. 4 | - IGenericTreeNode.InsertChildren(ushort position, T[] nodesData) to allow insertion of nodes at any 5 | position in the list of child nodes of the node. -------------------------------------------------------------------------------- /FluentSimpleTree.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30114.105 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{96D32199-BA65-433D-8B3E-26C43EE3CF71}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FluentSimpleTree", "src\FluentSimpleTree\FluentSimpleTree.csproj", "{AEE57294-581B-40B4-A605-EB1FF5E5A995}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(SolutionProperties) = preSolution 16 | HideSolutionNode = FALSE 17 | EndGlobalSection 18 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 19 | {AEE57294-581B-40B4-A605-EB1FF5E5A995}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 20 | {AEE57294-581B-40B4-A605-EB1FF5E5A995}.Debug|Any CPU.Build.0 = Debug|Any CPU 21 | {AEE57294-581B-40B4-A605-EB1FF5E5A995}.Release|Any CPU.ActiveCfg = Release|Any CPU 22 | {AEE57294-581B-40B4-A605-EB1FF5E5A995}.Release|Any CPU.Build.0 = Release|Any CPU 23 | EndGlobalSection 24 | GlobalSection(NestedProjects) = preSolution 25 | {AEE57294-581B-40B4-A605-EB1FF5E5A995} = {96D32199-BA65-433D-8B3E-26C43EE3CF71} 26 | EndGlobalSection 27 | EndGlobal 28 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) SyntaxChecked Group 2 | 3 | All rights reserved. 4 | 5 | Permission to use, copy, and/or distribute this software for any purpose with or without fee is hereby granted. 6 | 7 | The above copyright notice and this permission notice shall be included in all 8 | copies or substantial portions of the Software. 9 | 10 | All softwares developed and distributed with this lib included must display the following acknowledgement: 11 | This product includes software developed by the SyntaxChecked Group and its 12 | contributors. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # FluentSimpleTree 2 | A library to handle n-ary trees in a simple and fluent way for .NET 3 | 4 | ### Links 5 | 6 | * [Documentation](https://github.com/syntaxchecked/FluentSimpleTree.Examples#readme) 7 | * [Changelog](https://github.com/syntaxchecked/FluentSimpleTree/blob/main/CHANGELOG.txt) 8 | -------------------------------------------------------------------------------- /src/FluentSimpleTree/FluentSimpleTree.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | netstandard2.1 4 | True 5 | enable 6 | Nullable 7 | FluentSimpleTree 8 | 1.0.3 9 | Carlos Eduardo Olivieri 10 | Syntax Checked Group 11 | true 12 | README.md 13 | Copyright © SyntaxChecked Group 14 | FluentSimpleTree 15 | Tree;DataStructure 16 | LICENSE.txt 17 | icon.png 18 | FluentSimpleTree 19 | This library helps creating and manipulating n-ary trees in a simple and fluent way. 20 | This library helps creating and manipulating n-ary trees in a simple and fluent way. 21 | 22 | 23 | true 24 | 25 | 26 | true 27 | true 28 | true 29 | snupkg 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /src/FluentSimpleTree/IGenericTreeNode.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace SyntaxChecked.FluentSimpleTree 5 | { 6 | /// Tree node interface that holds data of generic type and performs handy operations. 7 | /// The type passed to IGenericTreeNode. 8 | public interface IGenericTreeNode 9 | { 10 | #region Data Members 11 | /// Property Id returns the node unique identifier, which is optional. 12 | string? Id { get; } 13 | 14 | /// Property Data holds the node data of generic type. 15 | T Data { get; set; } 16 | 17 | /// Property Parent returns the parent node. 18 | /// Thrown when the node is the root node. 19 | IGenericTreeNode Parent { get; } 20 | 21 | /// Property PrecedingSibling returns the preceding sibling node. 22 | /// Thrown when the node is the first child. 23 | IGenericTreeNode PrecedingSibling { get; } 24 | 25 | /// Property NextSibling returns the next sibling node. 26 | /// Thrown when the node is the last child. 27 | IGenericTreeNode NextSibling { get; } 28 | 29 | /// Property Level returns the node level. Root node has level = 0. 30 | ushort Level { get; } 31 | 32 | /// Property IsRootNode returns true if the node is the root node; otherwise, false. 33 | bool IsRootNode { get; } 34 | 35 | /// Property Index returns the position index of the node among its parent's child nodes. 36 | ushort Index { get; } 37 | 38 | #endregion 39 | 40 | /// Adds each node of type from as children of the current node instance. 41 | /// The array of generic nodes to add. 42 | /// An array of IGenericTreeNode<> that contains nodes that were added. 43 | IGenericTreeNode[] AddChildren(T[] nodesData); 44 | 45 | /// Adds each node in as children of the current node instance. 46 | /// An array of tuples (string nodeId, T data) to add. 47 | /// An array of IGenericTreeNode<> that contains nodes that were added. 48 | IGenericTreeNode[] AddChildren((string nodeId, T data)[] nodesData); 49 | 50 | /// 51 | /// Inserts each node of type from as children of the current node instance at the 52 | /// specified position by 53 | /// 54 | /// The index of . 55 | /// The array of generic nodes to insert. 56 | /// An array of IGenericTreeNode<> that contains nodes that were inserted. 57 | IGenericTreeNode[] InsertChildren(ushort position, (string nodeId, T data)[] nodesData); 58 | 59 | /// 60 | /// Inserts each node of type from as children of the current node instance at the 61 | /// specified position by 62 | /// 63 | /// The index of . 64 | /// An array of tuples (string nodeId, T data) to add. 65 | /// An array of IGenericTreeNode<> that contains nodes that were inserted. 66 | IGenericTreeNode[] InsertChildren(ushort position, T[] nodesData); 67 | 68 | /// Determines whether there exists the child node by informed. 69 | /// An index number. 70 | /// true if the current node instance has the child searched by the ; otherwise, false. 71 | bool HasChild(uint index); 72 | 73 | /// Determines whether there exists the child node by informed. 74 | /// An unique identifier. 75 | /// true if the current node instance has the child with the ; otherwise, false. 76 | bool HasChild(string nodeId); 77 | 78 | /// Determines whether there exists the descendant node by informed. 79 | /// An unique identifier. 80 | /// true if the current node instance has the descendant node; otherwise, false. 81 | bool HasDescendant(string nodeId); 82 | 83 | /// Determines whether there exists a preceding sibling node. 84 | /// true if the current node instance has a preceding sibling one; otherwise, false. 85 | bool HasPrecedingSibling(); 86 | 87 | /// Determines whether there exists a next sibling node. 88 | /// true if the current node instance has a next sibling one; otherwise, false. 89 | bool HasNextSibling(); 90 | 91 | /// Returns the child node by informed. 92 | /// An index number. 93 | /// Thrown when the child node cannot be found by the given index. 94 | IGenericTreeNode GetChild(uint index); 95 | 96 | /// Returns the child node by informed. 97 | /// An unique identifier. 98 | /// Thrown when the child node cannot be found by the given id. 99 | IGenericTreeNode GetChild(string nodeId); 100 | 101 | /// 102 | /// Returns an array of IGenericTreeNode<> according to . 103 | /// 104 | /// If no node is found according to , an empty array is returned. 105 | /// A custom search criteria based on a predicate according to the data type of the tree nodes. 106 | IGenericTreeNode[] GetChildren(Func searchCriteria); 107 | 108 | /// 109 | /// Returns an array of IGenericTreeNode<> containing all the children of the current node instance. 110 | /// 111 | IGenericTreeNode[] GetAllChildren(); 112 | 113 | /// Returns the descendant node by informed. 114 | /// An unique identifier. 115 | /// Thrown when the descendant node is not found by . 116 | IGenericTreeNode GetDescendant(string nodeId); 117 | 118 | /// 119 | /// Returns an array of IGenericTreeNode<> according to . 120 | /// 121 | /// If no node is found according to , an empty array is returned. 122 | /// A custom search criteria based on a predicate according to the data type of the tree nodes. 123 | IGenericTreeNode[] GetDescendants(Func searchCriteria); 124 | 125 | /// 126 | /// Returns an array of IGenericTreeNode<> containing all the descendants of the current node instance. 127 | /// 128 | IGenericTreeNode[] GetAllDescendants(); 129 | 130 | /// 131 | /// Removes the current node instance from the tree and returns it. 132 | /// 133 | IGenericTreeNode Remove(); 134 | 135 | /// Removes the child node by from the current instance node. 136 | /// An index number. 137 | /// The IGenericTreeNode<> that was removed. 138 | /// Thrown when the child node cannot be found by the given index. 139 | IGenericTreeNode RemoveChild(uint index); 140 | 141 | /// Removes the child node by from the current instance node. 142 | /// An unique identifier. 143 | /// The IGenericTreeNode<> that was removed. 144 | /// Thrown when the child node cannot be found by the given id. 145 | IGenericTreeNode RemoveChild(string nodeId); 146 | 147 | /// Removes the children nodes according to from the current instance node. 148 | /// A custom search criteria based on a predicate according to the data type of the tree nodes. 149 | /// An array of IGenericTreeNode<> that contains child nodes that were removed. 150 | IGenericTreeNode[] RemoveChildren(Func searchCriteria); 151 | 152 | /// 153 | /// Removes and returns an array of IGenericTreeNode<> containing all the children nodes removed from the current node instance. 154 | /// 155 | IGenericTreeNode[] RemoveAllChildren(); 156 | 157 | /// Removes the descendant node by from the current instance node. 158 | /// An unique identifier. 159 | /// The IGenericTreeNode<> that was removed. 160 | /// Thrown when the descendant node cannot be found by the given id. 161 | IGenericTreeNode RemoveDescendant(string nodeId); 162 | 163 | /// Removes the descendants nodes according to from the current instance node. 164 | /// A custom search criteria based on a predicate according to the data type of the tree nodes. 165 | /// An array of IGenericTreeNode<> that contains descendant nodes that were removed. 166 | IGenericTreeNode[] RemoveDescendants(Func searchCriteria); 167 | 168 | /// 169 | /// Removes and returns an array of IGenericTreeNode<> containing all the descendant nodes removed from the current node instance. 170 | /// 171 | IGenericTreeNode[] RemoveAllDescendants(); 172 | 173 | /// Appends a collection of nodes of type to the current node instance. 174 | /// This method is intended to be used with a collection of previously removed nodes. 175 | /// An collection of IGenericTreeNode<> 176 | /// An array of IGenericTreeNode<> that contains nodes that were not appended. 177 | /// 178 | IGenericTreeNode[] AppendNodes(IEnumerable> nodes); 179 | } 180 | } -------------------------------------------------------------------------------- /src/FluentSimpleTree/Tree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text.RegularExpressions; 5 | 6 | namespace SyntaxChecked.FluentSimpleTree 7 | { 8 | /// A generic n-ary tree class. 9 | /// The type stored by the tree nodes. 10 | public class Tree 11 | { 12 | #region Data Members 13 | private readonly Dictionary _nodesWithIds = new Dictionary(); 14 | 15 | /// Property RootNode returns the tree root node. It is assigned on class Tree instantiation. 16 | public IGenericTreeNode RootNode { get; private set; } 17 | 18 | /// Property Height returns the tree height. 19 | public ushort Height { get; private set; } 20 | 21 | #endregion //Data Members 22 | 23 | #region Methods 24 | /// 25 | /// Initializes the new tree with one root node containing the value passed to 26 | /// and whose Id is "root". 27 | /// 28 | /// The data stored in the node. 29 | public Tree(T rootNodeData) => RootNode = new TreeNode("root", rootNodeData, null, this); 30 | 31 | /// Initializes the new tree with one root node whose Id is "root". 32 | public Tree() => RootNode = new TreeNode("root", null, this); 33 | 34 | /// 35 | /// Determines whether the tree contains one node with informed. 36 | /// 37 | /// The node unique identifier. 38 | /// true if the tree contains one node with the given id; otherwise, false. 39 | /// 40 | /// Example: 41 | /// 42 | /// var myTree = new Tree<int>(1); 43 | /// if (myTree.HasNode("root")) //always returns true in this case 44 | /// System.Console.WriteLine("True"); 45 | /// 46 | /// 47 | public bool HasNodeById(string nodeId) 48 | { 49 | TreeNode.ValidateNodeId(nodeId); 50 | return _nodesWithIds.Any(item => item.Key == nodeId); 51 | } 52 | 53 | /// Returns the node by informed. 54 | /// The node unique identifier. 55 | /// Thrown when the node cannot be found by the given id. 56 | /// 57 | /// Example: 58 | /// 59 | /// var myTree = new Tree<int>(1); 60 | /// var root = myTree.GetNode("root"); 61 | /// System.Console.WriteLine(root.Data); 62 | /// 63 | /// 64 | public IGenericTreeNode GetNodeById(string nodeId) 65 | { 66 | try 67 | { 68 | TreeNode.ValidateNodeId(nodeId); 69 | return _nodesWithIds.First(item => item.Key == nodeId).Value; 70 | } 71 | catch 72 | { 73 | throw new Exception("The node cannot be found by id."); 74 | } 75 | } 76 | 77 | /// Returns an array of nodes according to informed. 78 | /// if no node is found by the search criteria, returns an empty array. 79 | /// A custom search criteria to find nodes based on a predicate according to data stored in the tree nodes. 80 | /// 81 | /// Example: 82 | /// 83 | /// var person1 = new Person("Carlos"); 84 | /// var person2 = new Person("Bruna"); 85 | /// var tree = new Tree<Person>(); 86 | /// tree.RootNode.AddChildren(new[] { person1, person2 }); 87 | /// var nodes = tree.GetNodes(person => person.Name == "Carlos"); 88 | /// System.Console.WriteLine($"{nodes.Length}"); //Output: 1 89 | /// 90 | /// 91 | public IGenericTreeNode[] GetNodes(Func searchCriteria) 92 | { 93 | var nodes = new List>(); 94 | 95 | if (RootNode.Data != null && searchCriteria(RootNode.Data)) 96 | nodes.Add(RootNode); 97 | 98 | nodes.AddRange(RootNode.GetDescendants(searchCriteria)); 99 | 100 | return nodes.ToArray(); 101 | } 102 | 103 | /// Returns an array of IGenericTreeNode<> containing all the tree nodes. 104 | public IGenericTreeNode[] GetAllNodes() => GetNodes(_ => true); 105 | 106 | #endregion //Methods 107 | 108 | private class TreeNode : IGenericTreeNode 109 | { 110 | #region Data Members 111 | 112 | //Private 113 | private readonly List _children; 114 | private readonly Tree _sourceTree; 115 | private TreeNode? _parent; 116 | private string? _id; 117 | private T _data; 118 | private ushort _level; 119 | 120 | //Public 121 | public string? Id 122 | { 123 | get => _id; 124 | private set 125 | { 126 | if (value != null) 127 | ValidateNodeId(value); 128 | 129 | _id = value; 130 | } 131 | } 132 | 133 | public T Data 134 | { 135 | get => _data; 136 | set => _data = value; 137 | } 138 | 139 | public IGenericTreeNode Parent 140 | { 141 | get => _parent ?? throw new Exception("Root node does not have parent."); 142 | private set => _parent = (TreeNode?)value; 143 | } 144 | 145 | public IGenericTreeNode PrecedingSibling 146 | { 147 | get 148 | { 149 | if (!HasPrecedingSibling()) 150 | throw new Exception("This node does not have previous siblings."); 151 | 152 | var leftSibling = _parent!._children[_parent._children.IndexOf(this) - 1]; 153 | return leftSibling; 154 | } 155 | } 156 | 157 | public IGenericTreeNode NextSibling 158 | { 159 | get 160 | { 161 | if (!HasNextSibling()) 162 | throw new Exception("This node does not have next siblings."); 163 | 164 | var righttSibling = _parent!._children[_parent._children.IndexOf(this) + 1]; 165 | return righttSibling; 166 | } 167 | } 168 | 169 | public ushort Level => _level; 170 | 171 | public bool IsRootNode => _parent == null; 172 | 173 | public ushort Index 174 | { 175 | get 176 | { 177 | if (IsRootNode) return 0; 178 | 179 | return (ushort)_parent!._children.IndexOf(this); 180 | } 181 | } 182 | 183 | #endregion //Data Members 184 | 185 | #region Methods 186 | 187 | //Publics 188 | public TreeNode(string? id, TreeNode? parent, Tree sourceTree) : this(id, default!, parent!, sourceTree) { } 189 | 190 | public TreeNode(string? id, T data, TreeNode? parent, Tree sourceTree) 191 | { 192 | _sourceTree = sourceTree; 193 | 194 | if (id != null) 195 | { 196 | if (_sourceTree._nodesWithIds.ContainsKey(id)) 197 | throw new Exception("There already exists a node having this id."); 198 | 199 | Id = id; 200 | _sourceTree._nodesWithIds.Add(id, this); 201 | } 202 | 203 | _parent = parent; 204 | _data = data; 205 | _children = new List(); 206 | 207 | _level = (ushort)(_parent == null 208 | ? 0 209 | : (_parent._level + 1)); 210 | } 211 | 212 | public IGenericTreeNode[] AddChildren((string nodeId, T data)[] nodesData) 213 | { 214 | var createdNodes = CreateChildren(nodesData); 215 | 216 | _children.AddRange((IEnumerable)createdNodes); 217 | 218 | return createdNodes; 219 | } 220 | 221 | public IGenericTreeNode[] AddChildren(T[] data) 222 | { 223 | var nodesData = data.SelectMany(item => new (string nodeId, T data)[] { (default!, item) }); 224 | 225 | return AddChildren(nodesData.ToArray()); 226 | } 227 | 228 | public IGenericTreeNode[] InsertChildren(ushort position, (string nodeId, T data)[] nodesData) 229 | { 230 | var createdNodes = CreateChildren(nodesData); 231 | 232 | if (position > _children.Count) 233 | AddChildren(nodesData); 234 | else 235 | _children.InsertRange(position, (IEnumerable)createdNodes); 236 | 237 | return createdNodes; 238 | } 239 | 240 | public IGenericTreeNode[] InsertChildren(ushort position, T[] data) 241 | { 242 | var nodesData = data.SelectMany(item => new (string nodeId, T data)[] { (default!, item) }); 243 | 244 | return InsertChildren(position, nodesData.ToArray()); 245 | } 246 | 247 | public bool HasChild(uint index) => index >= 0 && index < _children.Count; 248 | 249 | public bool HasChild(string nodeId) 250 | { 251 | ValidateNodeId(nodeId); 252 | return _children.Any(item => item._id == nodeId); 253 | } 254 | 255 | public bool HasDescendant(string nodeId) => HasDescendant(nodeId, this); 256 | 257 | public bool HasPrecedingSibling() 258 | => _parent != null && _parent._children.IndexOf(this) > 0; 259 | 260 | public bool HasNextSibling() 261 | => _parent != null && _parent._children.IndexOf(this) < _parent._children.Count - 1; 262 | 263 | public IGenericTreeNode GetChild(uint index) 264 | { 265 | if (!HasChild(index)) 266 | throw new Exception($"Child node not found by index: {index}."); 267 | 268 | return _children[(int)index]; 269 | } 270 | 271 | public IGenericTreeNode GetChild(string nodeId) 272 | { 273 | try 274 | { 275 | ValidateNodeId(nodeId); 276 | return _children.First(item => item.Id == nodeId); 277 | } 278 | catch 279 | { 280 | throw new Exception($"Child node not found by the id: {nodeId}."); 281 | } 282 | } 283 | 284 | public IGenericTreeNode[] GetAllChildren() => _children.Where(_ => true).ToArray(); 285 | 286 | public IGenericTreeNode[] GetChildren(Func searchCriteria) => _children.Where(item => searchCriteria(item._data)).ToArray(); 287 | 288 | public IGenericTreeNode GetDescendant(string nodeId) => GetDescendant(nodeId, this)!; 289 | 290 | public IGenericTreeNode[] GetDescendants(Func searchCriteria) 291 | { 292 | _ = searchCriteria ?? throw new ArgumentException("Argument searchCriteria cannot be null."); 293 | 294 | var descendantsNodes = new List>(); 295 | 296 | SearchForDescendants(searchCriteria, descendantsNodes); 297 | 298 | return descendantsNodes.ToArray(); 299 | } 300 | 301 | public IGenericTreeNode[] GetAllDescendants() => GetDescendants(_ => true); 302 | 303 | public IGenericTreeNode Remove() 304 | { 305 | _ = _parent ?? throw new Exception($"Root node can not be removed."); 306 | 307 | return _parent.RemoveChild(_parent._children.IndexOf(this), null); 308 | } 309 | 310 | public IGenericTreeNode RemoveChild(uint index) => RemoveChild((int)index, null); 311 | 312 | public IGenericTreeNode RemoveChild(string nodeId) => RemoveChild(-1, nodeId); 313 | 314 | public IGenericTreeNode[] RemoveChildren(Func searchCriteria) 315 | { 316 | var childrenToRemove = _children.Where(item => searchCriteria(item._data)); 317 | 318 | childrenToRemove 319 | .ToList() 320 | .ForEach(item => 321 | { 322 | item._parent = null; 323 | _children.Remove(item); 324 | 325 | if (item._id != null) 326 | _sourceTree._nodesWithIds.Remove(item._id); 327 | } 328 | ); 329 | 330 | return childrenToRemove.ToArray(); 331 | } 332 | 333 | public IGenericTreeNode[] RemoveAllChildren() => RemoveChildren(_ => true); 334 | 335 | public IGenericTreeNode RemoveDescendant(string nodeId) 336 | { 337 | var descendantNode = (TreeNode)GetDescendant(nodeId); 338 | 339 | descendantNode._parent?.RemoveChild(nodeId); 340 | 341 | return descendantNode; 342 | } 343 | 344 | public IGenericTreeNode[] RemoveDescendants(Func searchCriteria) 345 | { 346 | var descendants = GetDescendants(searchCriteria); 347 | 348 | var removedNodes = new List>(); 349 | 350 | while (descendants.Any()) 351 | { 352 | var queryParentNodes = descendants 353 | .Select(node => new 354 | { 355 | parentNode = node.Parent 356 | }) 357 | .Distinct() 358 | .ToList(); 359 | 360 | removedNodes.AddRange(queryParentNodes[0].parentNode.GetChildren(searchCriteria)); 361 | 362 | queryParentNodes[0].parentNode.RemoveChildren(searchCriteria); 363 | 364 | descendants = GetDescendants(searchCriteria); 365 | } 366 | 367 | return removedNodes.ToArray(); 368 | } 369 | 370 | public IGenericTreeNode[] RemoveAllDescendants() => RemoveDescendants(_ => true); 371 | 372 | public IGenericTreeNode[] AppendNodes(IEnumerable> nodes) 373 | { 374 | _ = nodes ?? throw new ArgumentException("Argument [nodes] cannot be null."); 375 | 376 | var nodesNotAppended = new List>(); 377 | 378 | nodes 379 | .ToList() 380 | .ForEach(item => 381 | { 382 | var node = (TreeNode)item; 383 | 384 | if (node._parent != null) 385 | { 386 | nodesNotAppended.Add(item); 387 | return; 388 | } 389 | 390 | if (node._id != null) 391 | { 392 | if (_sourceTree._nodesWithIds.ContainsKey(node._id)) 393 | { 394 | nodesNotAppended.Add(item); 395 | return; 396 | } 397 | 398 | _sourceTree._nodesWithIds.Add(node._id, (TreeNode)item); 399 | } 400 | 401 | node._parent = this; 402 | node._level = (ushort)(node._parent._level + 1); 403 | 404 | _children.Add(node); 405 | } 406 | ); 407 | 408 | return nodesNotAppended.ToArray(); 409 | } 410 | 411 | public static void ValidateNodeId(string id) 412 | { 413 | _ = id ?? throw new ArgumentException("Argument nodeId cannot be null."); 414 | 415 | var regex = new Regex(@"^[a-zA-Z0-9_][a-zA-Z0-9._-]*$"); 416 | 417 | if (!regex.IsMatch(id)) 418 | throw new FormatException("Invalid identifier."); 419 | } 420 | 421 | //Privates 422 | 423 | private IGenericTreeNode[] CreateChildren((string id, T data)[] nodesData) 424 | { 425 | TreeNode tnode; 426 | var newNodes = new List(); 427 | 428 | if (nodesData.Any() && _sourceTree.Height == _level) _sourceTree.Height++; 429 | 430 | nodesData.ToList().ForEach(item => 431 | { 432 | tnode = new TreeNode(item.id, item.data, this, _sourceTree); 433 | newNodes.Add(tnode); 434 | }); 435 | 436 | return newNodes.ToArray(); 437 | } 438 | 439 | private bool HasDescendant(string nodeId, TreeNode startingNode) 440 | { 441 | try 442 | { 443 | GetDescendant(nodeId, startingNode); 444 | return true; 445 | } 446 | catch 447 | { 448 | return false; 449 | } 450 | } 451 | 452 | private IGenericTreeNode GetDescendant(string nodeId, TreeNode startingNode) 453 | { 454 | TreeNode? descendantNode = null; 455 | 456 | if (_sourceTree.HasNodeById(nodeId)) 457 | { 458 | var targetNode = (TreeNode)_sourceTree.GetNodeById(nodeId); 459 | 460 | if (targetNode._level > startingNode._level) 461 | { 462 | TreeNode currentNode; 463 | ushort currentLevel; 464 | 465 | for (currentNode = targetNode, currentLevel = targetNode._level; currentLevel > startingNode._level; currentLevel--) 466 | { 467 | if (currentNode!._parent == startingNode) 468 | { 469 | descendantNode = targetNode; 470 | break; 471 | } 472 | currentNode = currentNode._parent!; 473 | } 474 | } 475 | } 476 | 477 | if (descendantNode == null) 478 | throw new Exception($"Descendant node not found by id. {nodeId}"); 479 | 480 | return descendantNode; 481 | } 482 | 483 | private void SearchForDescendants(Func searchCriteria, List> descendantsFound) 484 | { 485 | var foundNodes = _children.Where(item => searchCriteria(item._data)); 486 | 487 | if (foundNodes.Any()) 488 | descendantsFound.AddRange(foundNodes); 489 | 490 | foreach (var child in _children) 491 | { 492 | if (child._children.Any()) 493 | child.SearchForDescendants(searchCriteria, descendantsFound); 494 | } 495 | } 496 | 497 | private IGenericTreeNode RemoveChild(int index, string? nodeId) 498 | { 499 | var childNode = nodeId != null 500 | ? (TreeNode)GetChild(nodeId) 501 | : (TreeNode)GetChild((uint)index); 502 | 503 | if (childNode._id != null) 504 | _sourceTree._nodesWithIds.Remove(childNode._id); 505 | 506 | _children.Remove(childNode); 507 | childNode._parent = null; 508 | 509 | return childNode; 510 | } 511 | 512 | #endregion //Methods 513 | } 514 | } 515 | } -------------------------------------------------------------------------------- /src/FluentSimpleTree/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/syntaxchecked/FluentSimpleTree/e05597444ac295f155629bab81e75008afb4ec3c/src/FluentSimpleTree/icon.png --------------------------------------------------------------------------------