Ranges and Indicies
C# 8 introduced ranges and indicies for slicing and indexing collections at runtime. These operators are missing in Expression Trees. To bridge the gap, .NEXT Metaprogramming library offers the following expressions:
- Index Expression allows to construct expression of type Index
- Range Expression allows to construct expression of type Range
- Element Access Expression allows to construct access to the individual element of the arbitrary collection using Index. This type of expression is based on Index Expression
- Slice Expression allows to obtain a slice of the arbitrary collection using Range. This type of expression is based on Range Expression.
Element Access and Slice expressions follow the same rules as described here for C# language so library types such as one-dimensional arrays and strings are supported out-of-the-box.
The following example demonstrates how to obtain individual character from string and slice the string:
using DotNext.Linq.Expressions;
using System.Linq.Expressions;
Expression stringValue = "Hello, world".Const();
var character = stringValue.ElementAt(2.Index(false));
var slice = stringValue.Slice(start: 0.Index(false), end: 1.Index(true));
//the code is equivalent to
var stringValue = "Hello, world";
var character = stringValue[new Index(2, false)];
var slice = stringValue[0..^1];
Index
, ElementAt
and Slice
are extension methods from ExpressionBuilder simplifying construction of Index Expressio, Element Access Expression and Slice Expression respectively.