LINQ Support
h5 provides comprehensive support for Language Integrated Query (LINQ), allowing you to write powerful queries over collections in C# that are compiled efficiently to JavaScript.
Getting Started
To use LINQ, simply import the System.Linq namespace:
using System.Linq;
This makes all standard LINQ extension methods available on IEnumerable<T>, List<T>, arrays, and other collection types.
Supported Operators
Most standard query operators are supported, including:
- Filtering:
Where,OfType - Projection:
Select,SelectMany - Sorting:
OrderBy,OrderByDescending,ThenBy,ThenByDescending - Grouping:
GroupBy - Joins:
Join,GroupJoin - Aggregation:
Count,Sum,Min,Max,Average,Aggregate - Set Operations:
Distinct,Union,Intersect,Except - Element Operations:
First,FirstOrDefault,Last,LastOrDefault,Single,SingleOrDefault,ElementAt - Conversion:
ToArray,ToList,ToDictionary,ToLookup - Quantifiers:
Any,All,Contains
Example
var numbers = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var evenSquares = numbers
.Where(n => n % 2 == 0)
.Select(n => n * n)
.OrderByDescending(n => n)
.ToList();
// Output: 100, 64, 36, 16, 4
foreach (var square in evenSquares)
{
Console.WriteLine(square);
}
Performance Considerations
While LINQ provides expressive syntax, keep in mind that JavaScript engines are optimized for imperative loops (for, forEach). For extremely performance-critical sections (e.g., game loops or heavy data processing), consider using standard loops instead of LINQ if profiling shows a bottleneck.
However, for most application logic, the readability and maintainability benefits of LINQ outweigh minor performance differences.
LINQ to Objects vs LINQ to SQL
Currently, h5 primarily supports LINQ to Objects. If you need to query a database or remote API using LINQ syntax, you would typically fetch the data first (e.g., as JSON) and then query it in memory using LINQ to Objects.