### InfiniteSequence Example Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Illustrates creating an infinite sequence starting from 1 with a step of 1, and then taking the first 5 elements to create a finite sequence. ```csharp var infinite = ValueEnumerable.InfiniteSequence(1, 1).Take(5); // 1, 2, 3, 4, 5 ``` -------------------------------- ### Unity ZLinq Installation Bash Source: https://github.com/cysharp/zlinq/blob/main/README.md Install the ZLinq.Unity package by referencing the git URL in your Unity project. ```bash https://github.com/Cysharp/ZLinq.git?path=src/ZLinq.Unity/Assets/ZLinq.Unity ``` -------------------------------- ### Install ZLinq.Godot Package Source: https://github.com/cysharp/zlinq/blob/main/README.md Install the ZLinq.Godot package using the .NET CLI. This command adds the necessary ZLinq functionalities for Godot projects. ```bash dotnet add package ZLinq.Godot ``` -------------------------------- ### Range Example Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Illustrates the usage of the Range method to create sequences of integers and DateTime objects with specified start, count, and step values. ```csharp var range = ValueEnumerable.Range(0, 5); // 0, 1, 2, 3, 4 var dates = ValueEnumerable.Range(DateTime.Now, 7, TimeSpan.FromDays(1)); ``` -------------------------------- ### Build ZLinq Project Source: https://github.com/cysharp/zlinq/blob/main/CLAUDE.md Use this command to build the ZLinq project. Ensure .NET SDK is installed. ```bash dotnet build ``` -------------------------------- ### Add ZLinq Package Source: https://github.com/cysharp/zlinq/blob/main/README.md Install the ZLinq NuGet package using the .NET CLI. ```bash dotnet add package ZLinq ``` -------------------------------- ### Add ZLinq.DropInGenerator Package Source: https://github.com/cysharp/zlinq/blob/main/README.md Install the ZLinq drop-in package using the .NET CLI. ```bash dotnet add package ZLinq.DropInGenerator ``` -------------------------------- ### Index Example Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Demonstrates how to use the Index method to retrieve elements with their corresponding indices and iterate through them. ```csharp var numbers = new[] { 10, 20, 30 }; var indexed = numbers.AsValueEnumerable().Index(); foreach (var (i, value) in indexed) { Console.WriteLine($"{i}: {value}"); } ``` -------------------------------- ### Add ZLinq FileSystem Package Source: https://github.com/cysharp/zlinq/blob/main/README.md Installs the ZLinq.FileSystem NuGet package using the .NET CLI. ```bash dotnet add package ZLinq.FileSystem ``` -------------------------------- ### Install ZLinq Unity Integration via Git Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/configuration.md Install the ZLinq Unity integration by referencing the Git URL in your project's manifest.json. This enables LINQ to Tree queries on Unity's GameObject/Transform and UI Toolkit VisualElements. ```bash https://github.com/Cysharp/ZLinq.git?path=src/ZLinq.Unity/Assets/ZLinq.Unity ``` -------------------------------- ### Sequence Example Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Demonstrates creating a sequence of integers from 1 to 5 with a step of 1 using the Sequence method. ```csharp var seq = ValueEnumerable.Sequence(1, 5, 1); // 1, 2, 3, 4, 5 ``` -------------------------------- ### Example ZLinqDropInAttribute Usage Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/types.md Example of applying the ZLinqDropInAttribute at the assembly level to specify the namespace and types for LINQ method generation. ```csharp [assembly: ZLinqDropIn("MyApp", DropInGenerateTypes.Array | DropInGenerateTypes.List)] ``` -------------------------------- ### Example ZLinqDropInExtensionAttribute Usage Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/types.md Example of marking a custom generic list class with ZLinqDropInExtensionAttribute to enable drop-in LINQ method generation for it. ```csharp [ZLinqDropInExtension] public class CustomList : IEnumerable { // implementation } ``` -------------------------------- ### Add ZLinq JSON Package Source: https://github.com/cysharp/zlinq/blob/main/README.md Installs the ZLinq.Json NuGet package using the .NET CLI. ```bash dotnet add package ZLinq.Json ``` -------------------------------- ### Take Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Returns the specified number of elements from the start of a sequence. ```APIDOC ## Take ### Description Returns the specified number of elements from the start of a sequence. ### Method Signature ```csharp public static ValueEnumerable, TSource> Take(this ValueEnumerable source, int count) ``` ### Parameters #### Path Parameters - **count** (int) - Required - Number of elements to return ### Request Example ```csharp var numbers = new[] { 1, 2, 3, 4, 5 }; var first3 = numbers.AsValueEnumerable().Take(3); ``` ### Response Returns a new ValueEnumerable containing the first `count` elements. ``` -------------------------------- ### ZLinq Drop-in Replacement Setup Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/QUICK-REFERENCE.md Configure ZLinq as a drop-in replacement to automatically enhance LINQ operations within a specified namespace. No explicit calls to AsValueEnumerable() are needed after setup. ```csharp // In AssemblyInfo.cs or top of Program.cs [assembly: ZLinqDropIn("MyApp", DropInGenerateTypes.Collection)] // Now in MyApp namespace, no AsValueEnumerable() needed namespace MyApp { var result = array.Where(x => x > 10).ToArray(); // Uses ZLinq } ``` -------------------------------- ### Reverse Example Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Demonstrates reversing the order of elements in a sequence using the Reverse operator. ```csharp var numbers = new[] { 1, 2, 3 }; var reversed = numbers.AsValueEnumerable().Reverse(); ``` -------------------------------- ### OrderBy Example Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Demonstrates sorting a sequence of numbers in ascending order using the OrderBy operator. ```csharp var source = new[] { 3, 1, 2 }; var sorted = source.AsValueEnumerable().OrderBy(x => x); ``` -------------------------------- ### Repeat Example Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Shows how to use the Repeat method to create a sequence where the number 5 is repeated three times. ```csharp var repeated = ValueEnumerable.Repeat(5, 3); // 5, 5, 5 ``` -------------------------------- ### Shuffle Example Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Demonstrates randomly shuffling the elements of a sequence using the Shuffle operator. ```csharp var numbers = new[] { 1, 2, 3, 4, 5 }; var shuffled = numbers.AsValueEnumerable().Shuffle(); ``` -------------------------------- ### DateTime/DateTimeOffset Range and Sequence Examples Source: https://github.com/cysharp/zlinq/blob/main/README.md Demonstrates the usage of Range, InfiniteSequence with DateTime and DateTimeOffset types. ```csharp // DateTime/DateTimeOffset example // 5/13, 5/14, 5/15, 5/16, 5/17, 5/18, 5/19 var daysOfweek = ValueEnumerable.Range(DateTime.Now, 7, TimeSpan.FromDays(1)); // 5/1, 5/2,...,5/31 var now = DateTime.Now; var calendarOfThisMonth = ValueEnumerable.Range(new DateTime(now.Year, now.Month, 1), DateTime.DaysInMonth(now.Year, now.Month), TimeSpan.FromDays(1)); // 5/1, 5/2,... var endlessDate = ValueEnumerable.InfiniteSequence(DateTime.Now, TimeSpan.FromDays(1)); ``` -------------------------------- ### Add ZLinq JSON Package Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/configuration.md Install the ZLinq.Json package to enable LINQ to Tree queries on System.Text.Json.Nodes.JsonNode objects. ```bash dotnet add package ZLinq.Json ``` -------------------------------- ### Add ZLinq Core Package Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/configuration.md Install the core ZLinq package to access base LINQ operators and value-based enumeration. ```bash dotnet add package ZLinq ``` -------------------------------- ### Add ZLinq File System Package Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/configuration.md Install the ZLinq.FileSystem package to enable LINQ to Tree queries on FileSystemInfo objects like FileInfo and DirectoryInfo. ```bash dotnet add package ZLinq.FileSystem ``` -------------------------------- ### Any Operator Examples Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Tests if any element in a collection satisfies a condition or if the collection is not empty. Useful for checking existence. ```csharp var numbers = new[] { 1, 2, 3 }; var hasAny = numbers.AsValueEnumerable().Any(); var hasEven = numbers.AsValueEnumerable().Any(x => x % 2 == 0); ``` -------------------------------- ### TakeWhile Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Returns elements from the start of a sequence as long as a specified condition is met. ```APIDOC ## TakeWhile ### Description Returns elements from the start of a sequence as long as a specified condition is met. ### Method Signature ```csharp public static ValueEnumerable, TSource> TakeWhile(this ValueEnumerable source, Func predicate) public static ValueEnumerable, TSource> TakeWhile(this ValueEnumerable source, Func predicate) ``` ### Parameters #### Path Parameters - **predicate** (Func or Func) - Required - The condition to test each element against. ### Request Example ```csharp var numbers = new[] { 1, 2, 3, 4, 2 }; var lessThan4 = numbers.AsValueEnumerable().TakeWhile(x => x < 4); ``` ### Response Returns a new ValueEnumerable containing elements that satisfy the predicate. ``` -------------------------------- ### Example of JoinToString Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Demonstrates how to use the JoinToString operator to concatenate elements of an array into a string with a specified separator. ```csharp var numbers = new[] { 1, 2, 3 }; var joined = numbers.AsValueEnumerable().JoinToString(", "); // "1, 2, 3" ``` -------------------------------- ### Take Elements from Start Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Use Take to retrieve a specified number of elements from the beginning of a sequence. It's useful for limiting results or processing initial items. ```csharp var numbers = new[] { 1, 2, 3, 4, 5 }; var first3 = numbers.AsValueEnumerable().Take(3); ``` -------------------------------- ### Example Usage of GroupBy Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Demonstrates how to use the GroupBy operator to group numbers by their value and then iterate through the groups to display the key and count of elements in each group. ```csharp var numbers = new[] { 1, 2, 2, 3, 3, 3 }; var grouped = numbers.AsValueEnumerable().GroupBy(x => x); foreach (var group in grouped) { Console.WriteLine($"Key: {group.Key}, Count: {group.Count()}"); } ``` -------------------------------- ### Add ZLinq Drop-in Generator Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/configuration.md Install the ZLinq.DropInGenerator package to enable source generation for automatic LINQ replacement. Requires .NET toolchain version 6.0+. ```bash dotnet add package ZLinq.DropInGenerator ``` -------------------------------- ### Add ZLinq Godot Integration Package Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/configuration.md Install the ZLinq.Godot package for LINQ to Tree queries on Godot Node hierarchies. Compatible with Godot 4.0+. ```bash dotnet add package ZLinq.Godot ``` -------------------------------- ### First Operator Examples Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Retrieves the first element of a collection or the first element that satisfies a condition. Throws an exception if the sequence is empty. ```csharp var numbers = new[] { 1, 2, 3 }; var first = numbers.AsValueEnumerable().First(); var firstEven = numbers.AsValueEnumerable().First(x => x % 2 == 0); ``` -------------------------------- ### Unity ZLinq GameObject Traversal Source: https://github.com/cysharp/zlinq/blob/main/README.md Example script demonstrating ZLinq's LINQ to GameObject functionality for traversing Unity GameObjects. ```csharp using ZLinq; public class SampleScript : MonoBehaviour { public Transform Origin; void Start() { Debug.Log("Ancestors--------------"); // Container, Root foreach (var item in Origin.Ancestors()) Debug.Log(item.name); Debug.Log("Children--------------"); // Sphere_A, Sphere_B, Group, Sphere_A, Sphere_B foreach (var item in Origin.Children()) Debug.Log(item.name); Debug.Log("Descendants--------------"); // Sphere_A, Sphere_B, Group, P1, Group, Sphere_B, P2, Sphere_A, Sphere_B foreach (var item in Origin.Descendants()) Debug.Log(item.name); Debug.Log("BeforeSelf--------------"); // C1, C2 foreach (var item in Origin.BeforeSelf()) Debug.Log(item.name); Debug.Log("AfterSelf--------------"); // C3, C4 foreach (var item in Origin.AfterSelf()) Debug.Log(item.name); } } ``` -------------------------------- ### ZLinq Usage Example: App-Namespace Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/configuration.md Demonstrates how LINQ methods are resolved differently based on the namespace. Methods within 'MyApp' use ZLinq, while those in 'OtherApp' use System.Linq. ```csharp namespace MyApp.Services { public class DataProcessor { public void Process() { var data = new[] { 1, 2, 3 }; // Uses ZLinq methods (Select, Where, etc.) var result = data.Select(x => x * 2); } } } namespace OtherApp { public class Worker { public void Work() { var data = new[] { 1, 2, 3 }; // Uses System.Linq (AsEnumerable not required) var result = data.Select(x => x * 2); } } } ``` -------------------------------- ### ZLinq Drop-in Usage Example Source: https://github.com/cysharp/zlinq/blob/main/README.md Demonstrates how ZLinq methods are automatically selected when using the drop-in generator. Code within the specified namespace (`MyApp`) uses ZLinq, while code outside (`NotMyApp`) uses standard LINQ. ```csharp using ZLinq; [assembly: ZLinqDropInAttribute("MyApp", DropInGenerateTypes.Everything)] // namespace under MyApp namespace MyApp.Foo { public class Bar { public static void Foo(IEnumerable source) { // ZLinq ValueEnumerable var seq = source.Select(x => x * 2).Shuffle(); using var e = seq.Enumerator; while (e.TryGetNext(out var current)) { Console.WriteLine(current); } } } } // not under MyApp namespace namespace NotMyApp { public class Baz { public static void Foo(IEnumerable source) { // IEnumerable var seq = source.Select(x => x * 2); // .Shuffle(); using var e = seq.GetEnumerator(); while (e.MoveNext()) { Console.WriteLine(e.Current); } } } } ``` -------------------------------- ### All Operator Example Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Checks if all elements in a collection satisfy a given condition. Use this to validate that every item meets a specific criteria. ```csharp var numbers = new[] { 2, 4, 6 }; var allEven = numbers.AsValueEnumerable().All(x => x % 2 == 0); ``` -------------------------------- ### Example Usage of ToLookup Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Illustrates the use of the ToLookup operator to create a lookup collection from an array of strings, grouping them by their first character. ```csharp var source = new[] { "apple", "apricot", "banana" }; var lookup = source.AsValueEnumerable().ToLookup(x => x[0]); ``` -------------------------------- ### Using PooledArray Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/types.md Example demonstrating how to use the PooledArray with a using statement to ensure it's returned to the ArrayPool. Accesses the Span and Memory properties. ```csharp using var pooled = source.AsValueEnumerable().ToArrayPool(); var span = pooled.Span; var memory = pooled.Memory; ``` -------------------------------- ### Where Operator Usage Example Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Demonstrates filtering elements using the Where operator with a simple modulo predicate and a predicate including the element index. ```csharp var source = new[] { 1, 2, 3, 4, 5 }; var evens = source.AsValueEnumerable().Where(x => x % 2 == 0); var filtered = source.AsValueEnumerable().Where((x, i) => i > 2); ``` -------------------------------- ### Build and Run Zlinq Benchmark via Commandline Source: https://github.com/cysharp/zlinq/blob/main/sandbox/Benchmark/README.md Build the project in Release configuration and run benchmarks filtering all tests. Ensure you are in the `sandbox/Benchmark` directory. ```bash dotnet build -c Release dotnet run -c Release --framework net9.0 --no-build --no-launch-profile -- --filter "*" ``` -------------------------------- ### Example of TryGetNonEnumeratedCount Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Shows how to use TryGetNonEnumeratedCount to get the element count of a ValueEnumerable if it can be determined without enumeration. The count is output via an 'out' parameter. ```csharp var source = new[] { 1, 2, 3 }.AsValueEnumerable(); if (source.TryGetNonEnumeratedCount(out var count)) { Console.WriteLine($"Count: {count}"); } ``` -------------------------------- ### InfiniteSequence Method Overloads Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Generates an infinite sequence starting from a given value with a specified step. Requires taking a finite number of elements using methods like Take. ```csharp public static ValueEnumerable, T> InfiniteSequence( T start, TStep step) where T : IAdditionOperators ``` ```csharp public static ValueEnumerable InfiniteSequence( DateTime start, TimeSpan step) ``` ```csharp public static ValueEnumerable InfiniteSequence( DateTimeOffset start, TimeSpan step) ``` -------------------------------- ### Get Node Path to Root Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-to-tree.md Construct the path from a node to the root by traversing ancestors, reversing the order, and selecting node names. This requires the `AncestorsAndSelf()` extension method. ```csharp var path = node.AncestorsAndSelf() .Reverse() .Select(n => n.Name) .ToArray(); ``` -------------------------------- ### Run ZLinq Benchmarks Source: https://github.com/cysharp/zlinq/blob/main/CLAUDE.md Navigate to the benchmark directory and run benchmarks using this command. Ensure you are in the 'sandbox/Benchmark' directory. ```bash cd sandbox/Benchmark dotnet run -c Release ``` -------------------------------- ### Skip Elements from Start Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Use Skip to omit a specified number of elements from the beginning of a sequence and return the remaining elements. This is useful for pagination or skipping headers. ```csharp var numbers = new[] { 1, 2, 3, 4, 5 }; var skip2 = numbers.AsValueEnumerable().Skip(2); ``` -------------------------------- ### Godot Node Traversal with ZLinq Source: https://github.com/cysharp/zlinq/blob/main/README.md Utilize ZLinq extensions for traversing Godot node hierarchies. This example shows how to access ancestors, children, descendants, and nodes before/after a specific node using ZLinq's LINQ to Node functionality. ```csharp using Godot; using ZLinq; public partial class SampleScript : Node2D { public override void _Ready() { var origin = GetNode("Container/Origin"); GD.Print("Ancestors--------------"); // Container, Root, root (Root Window) foreach (var item in origin.Ancestors()) GD.Print(item.Name); GD.Print("Children--------------"); // Sphere_A, Sphere_B, Group, Sphere_A, Sphere_B foreach (var item in origin.Children()) GD.Print(item.Name); GD.Print("Descendants--------------"); // Sphere_A, Sphere_B, Group, P1, Group, Sphere_B, P2, Sphere_A, Sphere_B foreach (var item in origin.Descendants()) GD.Print(item.Name); GD.Print("BeforeSelf--------------"); // C1, C2 foreach (var item in origin.BeforeSelf()) GD.Print(item.Name); GD.Print("AfterSelf--------------"); // C3, C4 foreach (var item in origin.AfterSelf()) GD.Print(item.Name); } } ``` -------------------------------- ### C# Select Operator Example Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Demonstrates using the Select operator to transform elements and to transform elements with their index. The second overload includes the element's index. ```csharp var numbers = new[] { 1, 2, 3 }; var squared = numbers.AsValueEnumerable().Select(x => x * x); var indexed = numbers.AsValueEnumerable().Select((x, i) => $"{i}: {x}"); ``` -------------------------------- ### Get Distinct Elements by Key Selector Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Use DistinctBy to get unique elements from a sequence based on a specified key. This is useful when uniqueness is determined by a property or calculated value. ```csharp public static ValueEnumerable, TSource> DistinctBy( this ValueEnumerable source, Func keySelector) ``` -------------------------------- ### Query File System with ZLinq Source: https://github.com/cysharp/zlinq/blob/main/README.md Demonstrates querying file system information using ZLinq's extension methods on DirectoryInfo and FileInfo. Requires ZLinq.FileSystem package. ```csharp using ZLinq; var root = new DirectoryInfo("C:\\Program Files (x86)\\Steam"); // FileSystemInfo(FileInfo/DirectoryInfo) can call `Ancestors`, `Children`, `Descendants`, `BeforeSelf`, `AfterSelf` var allDlls = root .Descendants() .OfType() .Where(x => x.Extension == ".dll"); var grouped = allDlls .GroupBy(x => x.Name) .Select(x => new { FileName = x.Key, Count = x.Count() }) .OrderByDescending(x => x.Count); foreach (var item in grouped) { Console.WriteLine(item); } ``` -------------------------------- ### Define FromInfiniteSequence struct Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/types.md Defines a generic FromInfiniteSequence struct for creating an infinite sequence starting from a given value with a specified step. Created by ValueEnumerable.InfiniteSequence(T start, TStep step). ```csharp public struct FromInfiniteSequence : IValueEnumerator ``` -------------------------------- ### Chaining ZLinq Queries in Godot Source: https://github.com/cysharp/zlinq/blob/main/README.md Chain LINQ to Objects queries with ZLinq extensions for advanced node filtering in Godot. This example demonstrates taking ancestors until a specific type is met and filtering children by type. ```csharp // get ancestors under a Window var ancestors = root.Ancestors().TakeWhile(x => x is not Window); // get FooScript under self childer objects and self var fooScripts = root.ChildrenAndSelf().OfType(); ``` -------------------------------- ### Get Preceding Sibling Nodes Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-to-tree.md Use BeforeSelf to get all sibling nodes that appear before the current node in the tree structure. This is useful for processing nodes that come earlier in the same parent's child list. ```csharp public static ValueEnumerable, T> BeforeSelf( this TTraverser traverser) where TTraverser : struct, ITraverser ``` ```csharp var preceding = node.BeforeSelf(); var previousNode = node.BeforeSelf().LastOrDefault(); ``` -------------------------------- ### Define generic FromSequence struct Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/types.md Defines a generic FromSequence struct for creating sequences between a start and end value with a specified step. Requires T to support addition and comparison operators. Created by ValueEnumerable.Sequence(T start, T endInclusive, TStep step). ```csharp public struct FromSequence : IValueEnumerator where T : IAdditionOperators, IComparisonOperators ``` -------------------------------- ### File System Traversal with ZLinq Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-to-tree.md Demonstrates querying descendant files and counting files by directory using ZLinq with FileSystemInfo. ```csharp using ZLinq; var root = new DirectoryInfo("C:\\Program Files"); // All descendant files with .dll extension var allDlls = root .Descendants() .OfType() .Where(x => x.Extension == ".dll"); // Count files by directory var fileCounts = root .Descendants() .OfType() .Select(dir => new { Path = dir.FullName, FileCount = dir.Children() .OfType() .Count() }); ``` -------------------------------- ### Fill Array with Sequential Numbers using SIMD Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/simd-operations.md Fills a destination array with sequential numbers using SIMD for significant performance gains over manual loops. Overloads are available to specify start and step values. ```csharp public static void VectorizedFillRange(this T[] destination) where T : INumberBase public static void VectorizedFillRange(this T[] destination, T start) where T : INumberBase public static void VectorizedFillRange(this T[] destination, T start, T step) where T : INumberBase ``` ```csharp using ZLinq.Simd; int[] numbers = new int[10000]; numbers.VectorizedFillRange(0, 1); // Fill with 0, 1, 2, ..., 9999 ``` -------------------------------- ### Import ZLinq Namespace Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/QUICK-REFERENCE.md Always include this using directive to access ZLinq extension methods. ```csharp using ZLinq; // Always required ``` -------------------------------- ### Contains Operator Example Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Verifies if a collection includes a specific element. This is efficient for checking membership. ```csharp var numbers = new[] { 1, 2, 3 }; var has2 = numbers.AsValueEnumerable().Contains(2); ``` -------------------------------- ### Run ZLinq Tests Source: https://github.com/cysharp/zlinq/blob/main/CLAUDE.md Execute ZLinq-specific tests using this command. For extensive System.Linq compatibility tests, use a separate command. ```bash # Run ZLinq-specific tests dotnet test tests/ZLinq.Tests/ # Run System.Linq compatibility tests (extensive) dotnet test tests/System.Linq.Tests/ # Run all tests dotnet test ``` -------------------------------- ### Verify Span Support Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/configuration.md Check if span support is enabled by attempting to get a span from the enumerator of an AsValueEnumerable(). ```csharp var arr = new int[] { 1, 2, 3 }; var enum = arr.AsValueEnumerable().Enumerator; if (enum.TryGetSpan(out var span)) { Console.WriteLine("Span support enabled"); } ``` -------------------------------- ### C# SelectMany Operator Example Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Demonstrates using the SelectMany operator to flatten a sequence of arrays into a single sequence. ```csharp var source = new[] { new[] { 1, 2 }, new[] { 3, 4 } }; var flattened = source.AsValueEnumerable() .SelectMany(arr => arr.AsValueEnumerable()); ``` -------------------------------- ### Run Zlinq Benchmark via GitHub Actions Source: https://github.com/cysharp/zlinq/blob/main/sandbox/Benchmark/README.md Execute Zlinq benchmarks using GitHub Actions workflows. Specify the branch, filter criteria, or custom configurations like TargetFrameworks or SystemLinq. ```pwsh $branchName = 'main' # Run benchmark with `Default` config gh workflow run benchmark.yaml --repo Cysharp/ZLinq --ref $branchName # Run benchmark with `Default` config with benchmark filter gh workflow run benchmark.yaml --repo Cysharp/ZLinq --ref $branchName -f filter=Benchmark.ReadMeBenchmark* # Run benchmark with `TargetFrameworks` config gh workflow run benchmark.yaml --repo Cysharp/ZLinq --ref $branchName -f config=TargetFrameworks # Run benchmark with `SystemLinq` config gh workflow run benchmark.yaml --repo Cysharp/ZLinq --ref $branchName -f config=SystemLinq ``` -------------------------------- ### AggregateBy Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Groups elements of a ValueEnumerable by a specified key and then applies an accumulator function to each group, starting with a seed value. ```APIDOC ## AggregateBy ### Description Groups elements of a ValueEnumerable by a specified key and then applies an accumulator function to each group, starting with a seed value. ### Method Signature ```csharp public static ValueEnumerable, (TKey, TAccumulate)> AggregateBy(this ValueEnumerable source, Func keySelector, TAccumulate seed, Func accumulator) ``` ### Example ```csharp var items = new[] { (key: "a", val: 1), (key: "a", val: 2), (key: "b", val: 3) }; var aggregated = items.AsValueEnumerable() .AggregateBy(x => x.key, 0, (acc, x) => acc + x.val); ``` ``` -------------------------------- ### ElementAt Operator Examples Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Retrieves the element at a specific zero-based index or using a System.Index. Useful for accessing elements by position. ```csharp var numbers = new[] { 1, 2, 3 }; var second = numbers.AsValueEnumerable().ElementAt(1); var last = numbers.AsValueEnumerable().ElementAt(^1); ``` -------------------------------- ### InfiniteSequence Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Generates an infinite sequence starting from a given value with a specified step. Supports generic types, DateTimes, and DateTimeOffsets. ```APIDOC ## InfiniteSequence (static) ### Description Generates an infinite sequence with a step. ### Method Signatures ```csharp public static ValueEnumerable, T> InfiniteSequence(T start, TStep step) where T : IAdditionOperators public static ValueEnumerable InfiniteSequence(DateTime start, TimeSpan step) public static ValueEnumerable InfiniteSequence(DateTimeOffset start, TimeSpan step) ``` ### Example ```csharp var infinite = ValueEnumerable.InfiniteSequence(1, 1).Take(5); // 1, 2, 3, 4, 5 ``` ``` -------------------------------- ### Running .NET 10 Benchmarks with GitHub Actions Source: https://github.com/cysharp/zlinq/blob/main/sandbox/Benchmark/README.md When running .NET 10 benchmarks via GitHub Actions, an additional input parameter `-f framework=net10.0` is required. ```pwsh $branchName = 'main' gh workflow run benchmark.yaml --repo Cysharp/ZLinq --ref $branchName -f framework=net10.0 ``` -------------------------------- ### Prepend an element to a sequence Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Adds an element to the beginning of a sequence. This operator is useful for inserting a value at the start of an existing sequence. ```csharp public static ValueEnumerable, TSource> Prepend( this ValueEnumerable source, TSource element) ``` -------------------------------- ### Basic ZLinq Usage with ValueEnumerable Source: https://github.com/cysharp/zlinq/blob/main/README.md Demonstrates basic LINQ operations using ZLinq's ValueEnumerable for zero-allocation. Ensure `AsValueEnumerable()` is called on the source. ```csharp using ZLinq; var seq = source .AsValueEnumerable() // only add this line .Where(x => x % 2 == 0) .Select(x => x * 3); foreach (var item in seq) { } ``` -------------------------------- ### Vectorized Fill Range with ZLinq.Simd Source: https://github.com/cysharp/zlinq/blob/main/README.md Demonstrates using VectorizedFillRange from ZLinq.Simd for efficient sequential number generation, outperforming traditional for loops. ```csharp using ZLinq.Simd; // Example usage (assuming T[] or Span is available) // VectorizedFillRange is equivalent to ValueEnumerable.Range().CopyTo() // This method is designed for performance using SIMD processing. ``` -------------------------------- ### Ordering and Min with IComparable Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/QUICK-REFERENCE.md Shows how to use `OrderBy()` and `Min()` operators on types that implement `IComparable` for ordered operations. ```csharp // IComparable - ordered types source.OrderBy(x => x.Key); source.Min(); ``` -------------------------------- ### Godot Node Traversal with ZLinq Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-to-tree.md Demonstrates iterating through descendant nodes, finding nodes of a specific type, and filtering nodes by property using ZLinq in Godot. ```csharp using ZLinq; using Godot; public partial class SampleScript : Node2D { public override void _Ready() { var origin = GetNode("Container/Origin"); // All descendant nodes foreach (var node in origin.Descendants()) { GD.Print(node.Name); } // Find all nodes of specific type var allAreas = origin .Descendants() .OfType(); // Filter by property var visibleNodes = origin .DescendantsAndSelf() .Where(n => n.Visible); } } ``` -------------------------------- ### OfType Operator Usage Example Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Illustrates filtering a mixed-type array to select only elements of the string type using the OfType operator. ```csharp var mixed = new object[] { 1, "two", 3, "four" }; var strings = mixed.AsValueEnumerable().OfType(); ``` -------------------------------- ### Basic LINQ Chain with Zero Allocation Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/README.md Demonstrates a simple LINQ chain using ZLinq's AsValueEnumerable for zero-allocation operations. This is useful for standard data processing where performance and memory efficiency are critical. ```csharp using ZLinq; // Simple LINQ chain - zero allocation var source = new[] { 1, 2, 3, 4, 5 }; var result = source .AsValueEnumerable() .Where(x => x % 2 == 0) .Select(x => x * 2) .ToArray(); // Result: [4, 8] ``` -------------------------------- ### Partition Collections Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/QUICK-REFERENCE.md Split collections into subsets using 'Take' for the first N elements, 'Skip' for elements after the first N, 'TakeLast' for the last N elements, 'TakeWhile' for elements matching a condition, and 'Chunk' for splitting into fixed-size chunks. ```csharp // Get first N elements var first5 = source.Take(5); // Skip first N elements var rest = source.Skip(2); // Get last N elements var last3 = source.TakeLast(3); // Get while condition true var lessThan10 = source.TakeWhile(x => x < 10); // Split into chunks var chunked = source.Chunk(100); ``` -------------------------------- ### ValueEnumerable Where Operator Source: https://github.com/cysharp/zlinq/blob/main/README.md Example of a `Where` operator extension method for `ValueEnumerable`. This method filters elements based on a predicate and returns a new `ValueEnumerable`. ```csharp public static ValueEnumerable, TSource> Where(this ValueEnumerable source, Func predicate) where TEnumerator : struct, IValueEnumerator, allows ref struct ``` -------------------------------- ### Run All Tests with dotnet test Source: https://github.com/cysharp/zlinq/blob/main/tests/System.Linq.Tests/README.md Execute all unit tests using the `dotnet test` command. Ensure the `Release` configuration and `net9.0` framework are specified. Disable TerminalLogger and capture output for verbose logs. ```bash dotnet test -c Release --framework net9.0 --no-build -tl:off -p:TestingPlatformCaptureOutput=false ``` -------------------------------- ### Get Set Intersection of Two Sequences Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md The Intersect method returns the set intersection of two sequences, containing only elements that are present in both. ```csharp public static ValueEnumerable, TSource> Intersect( this ValueEnumerable source, ValueEnumerable<...> other) ``` -------------------------------- ### Enabling SIMD with AsValueEnumerable Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/as-value-enumerable.md Illustrates how AsValueEnumerable can automatically utilize SIMD operations for types supporting TryGetSpan(), leading to performance gains in .NET 8+. ```csharp var sum = array.AsValueEnumerable().Sum(); // Uses SIMD in .NET 8+ ``` -------------------------------- ### Count Elements in ZLINQ Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/QUICK-REFERENCE.md Use Count() to get the total number of elements or Count(predicate) to count elements that satisfy a condition. ```csharp int count = source.Count(); int even = source.Count(x => x % 2 == 0); ``` -------------------------------- ### Configure ZLinq DropInExternalExtension for Unity Native Collections Source: https://github.com/cysharp/zlinq/blob/main/README.md Extend ZLinq's DropInGenerator to support Unity's Native Collections by defining external extensions. This allows ZLinq to process types like NativeArray and NativeSlice. ```csharp [assembly: ZLinqDropInExternalExtension("ZLinq", "Unity.Collections.NativeArray`1", "ZLinq.Linq.FromNativeArray`1")] [assembly: ZLinqDropInExternalExtension("ZLinq", "Unity.Collections.NativeArray`1+ReadOnly", "ZLinq.Linq.FromNativeArray`1")] [assembly: ZLinqDropInExternalExtension("ZLinq", "Unity.Collections.NativeSlice`1", "ZLinq.Linq.FromNativeSlice`1")] [assembly: ZLinqDropInExternalExtension("ZLinq", "Unity.Collections.NativeList`1", "ZLinq.Linq.FromNativeList`1"] ``` -------------------------------- ### Sequence Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Generates a sequence from a start value to an end value (inclusive) with a specified step. Supports generic types, DateTimes, and DateTimeOffsets. ```APIDOC ## Sequence (static) ### Description Generates a sequence from start to end with a step. ### Method Signatures ```csharp public static ValueEnumerable, T> Sequence(T start, T endInclusive, TStep step) where T : IAdditionOperators, IComparisonOperators public static ValueEnumerable Sequence(DateTime start, DateTime endInclusive, TimeSpan step) public static ValueEnumerable Sequence(DateTimeOffset start, DateTimeOffset endInclusive, TimeSpan step) ``` ### Example ```csharp var seq = ValueEnumerable.Sequence(1, 5, 1); // 1, 2, 3, 4, 5 ``` ``` -------------------------------- ### Get Set Union of Two Sequences Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md The Union method returns the set union of two sequences, combining elements from both while ensuring uniqueness. ```csharp public static ValueEnumerable, TSource> Union( this ValueEnumerable source, ValueEnumerable<...> other) ``` -------------------------------- ### Aggregate Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Applies an accumulator function over all elements in a ValueEnumerable, starting with a specified seed value. It can also transform the accumulated result into a different type. ```APIDOC ## Aggregate ### Description Applies an accumulator function over all elements in a ValueEnumerable, starting with a specified seed value. It can also transform the accumulated result into a different type. ### Method Signatures ```csharp public static TAccumulate Aggregate(this ValueEnumerable source, TAccumulate seed, Func accumulator) public static TResult Aggregate(this ValueEnumerable source, TAccumulate seed, Func accumulator, Func resultSelector) ``` ### Example ```csharp var numbers = new[] { 1, 2, 3, 4 }; var sum = numbers.AsValueEnumerable().Aggregate(0, (acc, x) => acc + x); ``` ``` -------------------------------- ### Use PooledArray ToArrayPool() Source: https://github.com/cysharp/zlinq/blob/main/README.md Demonstrates renting an array from ArrayPool.Shared using ToArrayPool() and accessing its properties. Ensure to use a 'using' statement for proper disposal. ```csharp using var array = ValueEnumerable.Range(1, 1000).ToArrayPool(); var size = array.Size; // same as Length/Count in other types var span = array.Span; var memory = array.Memory; var arraySegment = array.ArraySegment; var enumerable = array.AsEnumerable(); var valueEnumerable = array.AsValueEnumerable(); ``` -------------------------------- ### Define FromRange struct for integers Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/types.md Defines the FromRange struct which implements IValueEnumerator. It is created by ValueEnumerable.Range(int start, int count). ```csharp public struct FromRange : IValueEnumerator ``` -------------------------------- ### Check Conditions with All/Any in ZLINQ Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/QUICK-REFERENCE.md Verify if all elements satisfy a condition using All() or if any element satisfies a condition using Any(). ```csharp bool allPositive = numbers.All(x => x > 0); bool anyNegative = numbers.Any(x => x < 0); ``` -------------------------------- ### JSON Traversal with ZLinq Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-to-tree.md Demonstrates finding all arrays, objects with a specific property, and all string values within a JSON structure using ZLinq. ```csharp using ZLinq; using System.Text.Json.Nodes; var json = JsonNode.Parse(jsonString); // Find all arrays in the JSON structure var allArrays = json .Descendants() .OfType(); // Find all objects with a specific property var objectsWithId = json .Descendants() .OfType() .Where(obj => obj.ContainsKey("id")); // Get all string values at any depth var allStrings = json .Descendants() .OfType() .Select(v => v.AsValue()) .OfType(); ``` -------------------------------- ### Get Set Difference of Two Sequences Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md The Except method returns the set difference between two sequences, containing elements that are in the first sequence but not in the second. ```csharp public static ValueEnumerable, TSource> Except( this ValueEnumerable source, ValueEnumerable<...> other) ``` -------------------------------- ### Get Distinct Elements from a Sequence Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-operators.md Use the Distinct method to retrieve unique elements from a sequence. An optional comparer can be provided for custom equality checks. ```csharp public static ValueEnumerable, TSource> Distinct( this ValueEnumerable source) ``` ```csharp public static ValueEnumerable, TSource> Distinct( this ValueEnumerable source, IEqualityComparer comparer) ``` ```csharp var numbers = new[] { 1, 2, 2, 3, 3, 3 }; var distinct = numbers.AsValueEnumerable().Distinct(); ``` -------------------------------- ### Safe Aggregation with Defaults Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/errors.md Demonstrates safe aggregation techniques. Check the count before performing operations like Average, or use Aggregate with an initial default value to handle empty collections gracefully. ```csharp var numbers = new int[0]; // Pattern 1: Check count first if (numbers.AsValueEnumerable().TryGetNonEnumeratedCount(out var count) && count > 0) { var average = numbers.AsValueEnumerable().Average(); } // Pattern 2: Use defaults/factories var sum = numbers.AsValueEnumerable().Aggregate(0, (acc, x) => acc + x); ``` -------------------------------- ### Get Element by Index in ZLINQ Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/QUICK-REFERENCE.md Access an element at a specific zero-based index using ElementAt(). Negative indices can be used to count from the end of the sequence. ```csharp // Get by index var third = source.ElementAt(2); var last = source.ElementAt(^1); // From end ``` -------------------------------- ### Get Last Element in ZLINQ Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/QUICK-REFERENCE.md Retrieve the last element of a sequence using Last(). Use LastOrDefault() to return a default value if the sequence is empty. ```csharp // Get last element var last = source.Last(); var lastOrNull = source.LastOrDefault(); ``` -------------------------------- ### Min and Max Elements in ZLINQ Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/QUICK-REFERENCE.md Find the minimum and maximum values in a collection using Min() and Max(). ```csharp int min = numbers.Min(); int max = numbers.Max(); ``` -------------------------------- ### Ancestors Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/linq-to-tree.md Returns all ancestor nodes up to the root, starting from the immediate parent. This method is part of the Tree Traversal Extension Methods in the `TraverserExtensions` static class. ```APIDOC ## Ancestors ### Description Returns all ancestor nodes up to the root. ### Method `Ancestors` ### Parameters This is an extension method, `traverser` is the instance it is called on. ### Returns `ValueEnumerable, T>` ### Remarks Returns ancestors from immediate parent up to root. Does not include the origin node. ### Example ```csharp var breadcrumb = node.Ancestors() .Reverse() .Select(n => n.Name) .ToArray(); ``` ``` -------------------------------- ### Import ZLinq SIMD Namespace Source: https://github.com/cysharp/zlinq/blob/main/_autodocs/api-reference/simd-operations.md Import the necessary namespace for explicit SIMD operations. ```csharp using ZLinq.Simd; ``` -------------------------------- ### Query JSON with ZLinq Source: https://github.com/cysharp/zlinq/blob/main/README.md Demonstrates querying JSON data using ZLinq's LINQ to JSON capabilities on System.Text.Json.JsonNode. Requires ZLinq.Json package. ```csharp using ZLinq; // System.Text.Json's JsonNode is the target of LINQ to JSON(not JsonDocument/JsonElement). var json = JsonNode.Parse(@"{ \"nesting\": { \"level1\": { \"description\": \"First level of nesting\", \"value\": 100, \"level2\": { \"description\": \"Second level of nesting\", \"flags\": [true, false, true], \"level3\": { \"description\": \"Third level of nesting\", \"coordinates\": { \"x\": 10.5, \"y\": 20.75, \"z\": -5.0 }, \"level4\": { \"description\": \"Fourth level of nesting\", \"metadata\": { \"created\": \"2025-02-15T14:30:00Z\", \"modified\": null, \"version\": 2.1 }, \"level5\": { \"description\": \"Fifth level of nesting\", \"settings\": { \"enabled\": true, \"threshold\": 0.85, \"options\": [\"fast\", \"accurate\", \"balanced\"], \"config\": { \"timeout\": 30000, \"retries\": 3, \"deepSetting\": { \"algorithm\": \"advanced\", \"parameters\": [1, 1, 2, 3, 5, 8, 13] } } } } } } } } } }"); // JsonNode var origin = json!["nesting"]!["level1"]!["level2"]!; // JsonNode axis, Children, Descendants, Anestors, BeforeSelf, AfterSelf and ***Self. foreach (var item in origin.Descendants().Select(x => x.Node).OfType()) { // [true, false, true], ["fast", "accurate", "balanced"], [1, 1, 2, 3, 5, 8, 13] Console.WriteLine(item.ToJsonString(JsonSerializerOptions.Web)); } ```