This nuget package provides extension functions for NCalc.
The NCalc documentation can be found here (source code) and here (good explanation of built-in functions).
When using ExtendedExpression, you can:
- use "//" comments
- split expressions over multiple lines
- include empty lines
- indent lines
For example:
// This calculates the presence of a needle in a haystack
contains(
// Complicated haystack creation
'haystack ' + 'containing needle',
// The needle we are looking for
'needle'
)
Starting with version 5.8, this library has migrated from CoreCLR-NCalc to the NCalcSync package.
This brings improved performance, better maintainability, and bug fixes, but requires awareness when upgrading.
Version numbers align with the NCalcSync package for clarity.
- NuGet Package Dependency: The underlying NCalc implementation changed from
CoreCLR-NCalctoNCalcSync - Target Framework: Now targets .NET 9 only (previously supported .NET Standard 2.0)
- Constructor Options:
ExtendedExpressionnow provides two constructors for different use cases
For most users, no code changes are required. The default constructor continues to work with sensible defaults:
using PanoramicData.NCalcExtensions;
var expression = new ExtendedExpression("1 + 1");
var result = expression.Evaluate(); // Returns: 2The default constructor automatically applies these ExpressionOptions:
ExpressionOptions.NoCache- Expressions are not cached (safer for dynamic expressions)ExpressionOptions.NoStringTypeCoercion- Prevents automatic string-to-number conversionsExpressionOptions.StrictTypeMatching- Enforces type safety (e.g.,1 != '1')
If you need custom ExpressionOptions, use the overloaded constructor:
using PanoramicData.NCalcExtensions;
using NCalc;
using System.Globalization;
var expression = new ExtendedExpression(
"1 + 1",
ExpressionOptions.None, // Or combine options with |
CultureInfo.InvariantCulture
);
var result = expression.Evaluate();The ExpressionOptions enum from NCalcSync provides fine-grained control over expression evaluation:
None: Default NCalc behavior (allows caching, type coercion, etc.)NoCache: Disables expression caching (recommended for dynamic expressions)NoStringTypeCoercion: Prevents implicit string-to-number conversionsStrictTypeMatching: Enforces strict type comparisonsIgnoreCase: Makes string comparisons case-insensitiveAllowNullParameter: Allows null parameter valuesIterateParameters: Enables parameter iteration in expressions
For complete documentation on ExpressionOptions, see the NCalcSync documentation.
The CoreCLR-NCalc package is no longer actively maintained. Migrating to NCalcSync provides:
- Active maintenance and bug fixes
- Better performance
- Improved standard compliance
- Enhanced type safety options
| Function | Purpose | Notes |
|---|---|---|
| all() | Returns true if all values match the lambda expression, otherwise false. | |
| any() | Returns true if any values match the lambda expression, otherwise false. | |
| canEvaluate() | Determines whether ALL of the parameters can be evaluated. This can be used, for example, to test whether a parameter is set. | |
| capitalize() | Capitalizes a string. | |
| cast() | Cast an object to another (e.g. float to decimal). | |
| changeTimeZone() | Change a DateTime's time zone. | |
| concat() | Concatenates lists and objects. | |
| contains() | Determines whether one string contains another. | |
| convert() | Converts the output of parameter 1 into the result of parameter 2. | |
| count() | Counts the number of items. Optionally, only count those that match a lambda. | |
| countBy() | Counts the number of items by a calculated term. | |
| dateAdd() | Add a specified interval to a DateTime. | |
| dateTime() | Return the DateTime in the specified format as a string, with an optional offset. | |
| dateTimeAsEpoch() | Parses the input DateTime and outputs as seconds since the Epoch (1970-01-01T00:00Z). | |
| dateTimeAsEpochMs() | Parses the input DateTime and outputs as milliseconds since the Epoch (1970-01-01T00:00Z). | |
| dateTimeIsInFuture() | Whether a DateTime is in the future, with an optional timezone correction. | |
| dateTimeIsInPast() | Whether a DateTime is in the past, with an optional timezone correction. | |
| dictionary() | Builds a Dictionary<string, object?> from the parameters provided. | |
| distinct() | Returns only distinct items from the input. | |
| endsWith() | Determines whether a string ends with another string. | |
| extend() | Extends an existing object into a JObject with both the original and additional properties. | |
| first() | Returns the first item in a list that matches a lambda or throws a FormatException if no items match. | |
| firstOrDefault() | Returns the first item in a list that matches a lambda or null if no items match. | |
| format() | Formats strings and numbers as output strings with the specified format. | |
| getProperties() | Returns a list of property names for an object. | |
| getProperty() | Returns the value of a given property. | |
| humanize() | Converts a value to a more readable format. | |
| if() | Return one of two values, depending on the input function. | |
| in() | Determines whether a value is in a set of other values. | |
| indexOf() | Determines the first position of a string within another string. | |
| isGuid() | Determines whether a value is a GUID, or is a string that can be converted to a GUID. | |
| isInfinite() | Determines whether a value is infinite. | |
| isNaN() | Determines whether a value is not a number. | |
| isNull() | Determines whether a value is null. | |
| isNullOrEmpty() | Determines whether a value is null or empty. | |
| isNullOrWhiteSpace() | Determines whether a value is null, empty or white space. | |
| isSet() | Determines whether a parameter is set. | |
| itemAtIndex() | Determines the item at the given index. | |
| jArray() | Creates a Newtonsoft JArray from input values. | |
| jObject() | Creates a JObject from key/value pairs. | |
| join() | Joins a list of strings into a single string. | |
| jsonArray() | Creates a System.Text.Json JsonDocument array from input values. | |
| jsonDocument() | Creates a System.Text.Json JsonDocument from key/value pairs. | |
| jPath() | Selects a single value from a JObject using a JPath expression | |
| last() | Determines the last value in an IEnumerable. Throws an Exception if no item matches. | |
| lastIndexOf() | Determines the last position of a string within another string. | |
| lastOrDefault() | Determines the last value in an IEnumerable. Returns null if no item matches. | |
| length() | Determines length of a string or IList. | |
| list() | Emits a List<object?> and collapses down lists of lists to a single list. | |
| listOf() | Emits a List<T>. | |
| max() | Emits the maximum value, ignoring nulls. | |
| maxValue() | Emits the maximum possible value for a given numeric or date/time type. | |
| min() | Emits the minimum value, ignoring nulls. | |
| minValue() | Emits the minimum possible value for a given numeric or date/time type. | |
| now() | Returns the current date and time, with optional timezone correction. | |
| nullCoalesce() | Returns the first parameter that is not null, otherwise: null. | |
| orderBy() | Orders an IEnumerable by one or more lambda expressions. | |
| padLeft() | Pad the left of a string with a character to a desired string length. | |
| parse() | Returns the conversion of a string to a new type. | |
| parseInt() | Returns an integer version of a string. | Deprecated - use parse() or tryParse() instead) |
| regexGroup() | Selects a regex group capture. | |
| regexIsMatch() | Determine whether a string matches a regex. | |
| replace() | Replace a string with another string. | |
| retrieve() | Retrieves a value from storage. | |
| reverse() | Reverses an IEnumerable and emits a List<object?>. | |
| sanitize() | Sanitizes a string, replacing any characters outside of the allowed set. | |
| select() | Converts an IEnumerable using a lambda. | |
| selectDistinct() | Converts an IEnumerable using a lambda and removes duplicates. | |
| setProperties() | Sets properties on an existing object. | |
| sha256() | Converts a string to a SHA256 hash. | |
| skip() | Skips a number of items in a list. | |
| sort() | Sorts an IComparable ascending or descending. | |
| split() | Splits a string on a given character into a list of strings. | |
| startsWith() | Determines whether a string starts with another string. | |
| store() | Stores a value for use later in the pipeline. | |
| substring() | Retrieves part of a string. | |
| sum() | Sums numeric items. | |
| switch() | Return one of a number of values, depending on the input function. | |
| take() | Takes a number of items from a list. | |
| throw() | Throws an NCalcExtensionsException. | |
| timeSpan() | Determines the amount of time between two DateTimes. | |
| toDateTime() | Converts a string to a UTC DateTime. May take an optional inputTimeZone. | |
| toLower() | Converts a string to lower case. | |
| toString() | Converts any object to a string. | |
| toUpper() | Converts a string to upper case. | |
| trim() | Removed leading and trailing whitespace. | |
| try() | If a function throws an exception, return an alternate value. | |
| tryParse() | Returns a boolean result of an attempted cast | |
| typeOf() | Determines the C# type of the object. | |
| where() | Filters an IEnumerable to bring back only those items that match a condition. |
using PanoramicData.NCalcExtensions;
...
var calculation = "lastIndexOf('abcdefg', 'def')";
var nCalcExpression = new ExtendedExpression(calculation);
if (nCalcExpression.HasErrors())
{
throw new FormatException($"Could not evaluate expression: '{calculation}' due to {nCalcExpression.Error}.");
}
return nCalcExpression.Evaluate();Note that we regularly extend this library to add new functions. For those that further extend the functions, it is important to avoid future potential namespace conflicts. For this reason, we guarantee that we will never use the underscore character in any future function name and we recommend that any functions that you add DO include an underscore. For example, if you had a project called "My Project", we suggest that you name your functions as follows:
- mp_myFunction1()
- mp_myFunction2()
Pull requests are welcome! Please submit your requests for new functions in the form of pull requests.
Returns true if all values match the lambda expression, otherwise false.
- list - the original list
- predicate - (optional) a string to represent the value to be evaluated
- nCalcString - (optional, but must be provided if predicate is) the string to evaluate
- all() : true
- all(list(false, false, false)) : false
- all(list(true, false, true)) : false
- all(list(true, true, true)) : true
- all(list(1, 2, 3, 4, 5), 'n', 'n < 3') : false
- all(list(1, 2, 3, 4, 5), 'n', 'n > 0 && n < 10') : true
Returns true if any values match the lambda expression, otherwise false.
- list - the original list
- predicate - (optional) a string to represent the value to be evaluated
- nCalcString - (optional, but must be provided if predicate is) the string to evaluate
- any(list()) : false
- any(list(1, 2, 3)) : true
- any(list(1, 2, 3, 4, 5), 'n', 'n < 3') : true
- any(list(1, 2, 3, 4, 5), 'n', 'n > 11') : false
Determines whether ALL of the parameters can be evaluated. This can be used, for example, to test whether a parameter is set.
- parameter1, parameter2, ...
- canEvaluate(nonExistent) : false
- canEvaluate(1) : true
Capitalizes a string.
- string
- capitalize('new year') : 'New Year'
Cast an object to another (e.g. float to decimal).
The method requires that conversion of value to target type be supported.
- inputObject
- typeString
- cast(0.3, 'System.Decimal')
Change a DateTime's time zone.
For a list of supported TimeZone names, see https://docs.microsoft.com/en-us/dotnet/api/system.timezoneinfo.findsystemtimezonebyid?view=netstandard-2.0
- source DateTime
- source TimeZone name
- destination TimeZone name
- changeTimeZone(theDateTime, 'UTC', 'Eastern Standard Time')
- changeTimeZone(theDateTime, 'Eastern Standard Time', 'UTC')
Concatenates lists and objects.
The examples all result in a List<object?> containing 4 integers: 1, 2, 3 and 4.
- the lists or objects to concatenate
- concat(list(1, 2), list(3, 4))
- concat(list(1, 2, 3, 4))
- concat(1, 2, 3, 4)
- concat(list(1, 2, 3), 4)
- concat(1, list(2, 3, 4))
Determines whether one string contains another.
- string searched-in text
- string searched-for text
- contains('haystack containing needle', 'needle') : true
- contains('haystack containing only hay', 'needle') : false
Converts the output of parameter 1 into the result of parameter 2.
Can be used to return an empty string instead of the result of parameter 1, which can be useful when the return value is not useful. The result of parameter 1 is available as the variable "value".
- the value to calculate
- destination TimeZone name
- convert(anyFunction(), 'XYZ'): 'XYZ'
- convert(1 + 1, value + 1): 3
Counts the number of items. Optionally, only count those that match a lambda.
- list - the original list
- predicate (optional) - a string to represent the value to be evaluated
- nCalcString (optional) - the string to evaluate
- count('a piece of string') : 17
- count(list(1, 2, 3, 4, 5)) : 5
- count(list(1, 2, 3, 4, 5), 'n', 'n > 3') : 2
Counts the number of items, grouped by a calculation.
- list - the original list
- predicate - a string to represent the value to be evaluated
- nCalcString - the string to evaluate. Must emit a string containing one or more characters: A-Z, a-z, 0-9 or _.
- countBy(list(1, 2, 2, 3, 3, 3, 4), 'n', 'toLower(toString(n > 1))') : { 'false': 1, 'true': 6 }
- countBy(list(1, 2, 2, 3, 3, 3, 4), 'n', 'toString(n)') : { '1': 1, '2': 2, '3', 3, '4', '1' }
Add a specified period to a DateTime. The following units are supported:
- Years
- Months
- Days
- Hours
- Minutes
- Seconds
- Milliseconds
- intialDateTime - A DateTime to which to add the period specified
- quantity - The integer number of the units to be added
- units - A string representing the units used to specify the period to be added
- dateAdd(toDateTime('2019-03-05 05:09', 'yyyy-MM-dd HH:mm'), -90, 'days') : 90 days before (2018-12-05 05:09:00)
- dateAdd(toDateTime('2019-03-05 01:03:05', 'yyyy-MM-dd HH:mm:ss'), 2, 'hours') : 2 hours later (2019-03-05 03:03:05)
Return the DateTime in the specified format as a string, with an optional offset.
- timeZone (only 'UTC' currently supported)
- format
- day offset
- hour offset
- minute offset
- second offset
- dateTime('UTC', 'yyyy-MM-dd HH:mm:ss', -90, 0, 0, 0) : 90 days ago (e.g. '2019-03-14 05:09')
- dateTime('UTC', 'yyyy-MM-dd HH:mm:ss') : now (e.g. '2019-03-14 05:09')
Parses the input DateTime and outputs as seconds since the Epoch (1970-01-01T00:00Z).
- input date string
- format
- dateTimeAsEpoch('20190702T000000', 'yyyyMMddTHHmmssK') : 1562025600
Parses the input DateTime and outputs as milliseconds since the Epoch (1970-01-01T00:00Z).
- input date string
- format
- dateTimeAsEpochMs('20190702T000000', 'yyyyMMddTHHmmssK') : 1562025600000
Returns whether a date and time is in the future, with optional timezone correction.
- The date and time under test * optionally, the name of the timezone that the date and time represents
- dateTimeIsInFuture(toDateTime('2001-01-01T00:00:00', 'YYYY-MM-ddTHH:mm:ss')) : false
- dateTimeIsInFuture(toDateTime('2201-01-01T00:00:00', 'YYYY-MM-ddTHH:mm:ss')) : true
- dateTimeIsInFuture(now(), 'Africa/Luanda') : false; UTC is never ahead of West Africa Time
Returns whether a date and time is in the past, with optional timezone correction.
- The date and time under test * optionally, the name of the timezone that the date and time represents
- dateTimeIsInPast(toDateTime('2001-01-01T00:00:00', 'YYYY-MM-ddTHH:mm:ss')) : true
- dateTimeIsInPast(toDateTime('2201-01-01T00:00:00', 'YYYY-MM-ddTHH:mm:ss')) : false
- dateTimeIsInPast(now(), 'Africa/Luanda') : true; UTC is always behind West Africa Time
Emits a Dictionary<string, object?>.
- interlaced keys and values. You must provide an even number of parameters, and keys must evaluate to strings.
- dictionary('KEY1', 'Hello', 'KEY2', 'Goodbye') : a dictionary containing 2 values with keys KEY1 and KEY2, and string values
- dictionary('TRUE', true, 'FALSE', false) : a dictionary containing 2 values with keys TRUE and FALSE, and boolean values
Returns only distinct items from the input.
- list - the original list
- distinct(list(1, 2, 3, 3, 3)) : list(1, 2, 3)
Determines whether a string ends with another string.
- longString
- shortString
- endsWith('abcdefg', 'fg') : true
- endsWith('abcdefg', 'fgh') : false
Extends an existing object into a JObject with both the original and additional properties.
- originalObject
- listOfAdditionalProperties
- extend(jObject('a', 1, 'b', null), list('c', 5)) : JObject with a=1, b=null and c=5
- extend(jObject('a', 1, 'b', null), list('c', null)) : JObject with a=1, b=null and c=null
Returns the first item in a list that matches a lambda or throws a FormatException if no items match.
- list
- predicate
- lambda expression as a string
- first(list(1, 5, 2, 3), 'n', 'n % 2 == 0') : 2
- first(list(1, 5, 7, 3), 'n', 'n % 2 == 0') : FormatException thrown
Returns the first item in a list that matches a lambda or null if no items match.
- list
- predicate
- lambda expression as a string
- firstOrDefault(list(1, 5, 2, 3), 'n', 'n % 2 == 0') : 2
- firstOrDefault(list(1, 5, 7, 3), 'n', 'n % 2 == 0') : null
Formats strings and numbers as output strings with the specified format.
- object (number or text)
- format: the format to use
- see C# number and date/time formatting
- weekOfMonth is the numeric week of month as would be shown on a calendar with one row per week with weeks starting on a Sunday
- weekOfMonthText is the same as weekOfMonth, but translated: 1: 'first', 2: 'second', 3: 'third', 4: 'forth', 5: 'last'
- weekDayOfMonth is the number of times this weekday has occurred within the month so far, including this one
- weekDayOfMonthText is the same as weekDayOfMonth, but translated: 1: 'first', 2: 'second', 3: 'third', 4: 'forth', 5: 'last'
- weekOfYear is the culture-specific week number of the year (1-53)
- isoWeekOfYear is the ISO 8601 week number of the year (1-53)
- timeZone [optional] - see https://docs.microsoft.com/en-us/dotnet/api/system.timezoneinfo.findsystemtimezonebyid?view=netstandard-2.0
- format(1, '00') : '01'
- format(1.0, '00') : '01'
- format('2021-11-29', 'dayOfYear') : '333'
- format('2021-11-01', 'weekOfMonth') : 1
- format('2021-11-01', 'weekOfMonthText') : 'first'
- format('2021-11-28', 'weekOfMonth') : 5
- format('2021-11-28', 'weekOfMonthText') : 'last'
- format('2021-11-28', 'weekDayOfMonth') : 4
- format('2021-11-28', 'weekDayOfMonthText') : 'forth'
- format('2024-01-01', 'weekOfYear') : '1' (can be controlled with CultureOptions, but defaults to CultureInfo.Invariant)
- format('2024-01-01', 'isoWeekOfYear') : '1'
- format('01/01/2019', 'yyyy-MM-dd') : '2019-01-01'
- format(theDateTime, 'yyyy-MM-dd HH:mm', 'Eastern Standard Time') [where theDateTime is a .NET DateTime, set to DateTime.Parse("2020-03-13 16:00", CultureInfo.InvariantCulture)] : '2020-03-13 12:00'
Gets a list of an object's properties.
Supports JObject, JsonDocument, JsonElement, and regular .NET objects.
- sourceObject
- getProperties(parse('jObject', '{ "A": 1, "B": 2 }')) : [ 'A', 'B' ]
- getProperties(jsonDocument('name', 'John', 'age', 30)) : [ 'name', 'age' ]
- getProperties(toDateTime('2019-01-01', 'yyyy-MM-dd')) : [ 'Date', 'Day', 'DayOfWeek', 'DayOfYear', 'Hour', 'Kind', 'Millisecond', 'Microsecond', 'Nanosecond', 'Minute', 'Month', 'Now', 'Second', 'Ticks', 'TimeOfDay', 'Today', 'Year', 'UtcNow' ]
Gets an object's property.
Supports JObject, JsonDocument, JsonElement, Dictionary<string, object?>, and regular .NET objects.
- sourceObject
- propertyName
- getProperty(toDateTime('2019-01-01', 'yyyy-MM-dd'), 'Year') : 2019 (int)
- getProperty(jsonDocument('name', 'John', 'age', 30), 'name') : 'John'
Humanizes the value text.
- value
- timeUnit
- humanize(3600, 'seconds') : '1 hour'
Return one of two values, depending on the input function.
- condition
- output if true
- output if false
- if(1 == 1, 'yes', 'no') : 'yes'
- if(1 == 2, 3, 4) : 4
Determines whether a value (the first parameter) is in a set of other values (the remaining parameters).
- item
- list
- in('needle', 'haystack', 'with', 'a', 'needle', 'in', 'it') : true
- in('needle', 'haystack', 'with', 'only', 'hay') : false
Determines the first position of a string within another string.
The first character is position 0. Returns -1 if not present.
- longString
- shortString
- indexOf('#abcabc#', 'abc') : 1
- indexOf('#abcabc#', 'abcd') : -1
Determines whether a value is a GUID, or is a string that can be converted to a GUID.
- value
- isGuid('9384EF0Z-38AD-4E8E-A24E-0ACD3273A401') : true
- isGuid('{9384EF0Z-38AD-4E8E-A24E-0ACD3273A401}') : true
- isGuid('abc') : false
Determines whether a value is infinite.
- value
- isInfinite(1/0) : true
- isInfinite(0/1) : false
Determines whether a value is not a number.
- value
- isNaN(null) : true
- isNaN('abc') : true
- isNaN(1) : false
Determines whether a value is null.
Returns true if the value is:
- null; or
- it's a JObject and it's type is JTokenType.Null; or
- it's a JsonElement and it's ValueKind is JsonValueKind.Null.
- value
- isNull(1) : false
- isNull('text') : false
- isNull(bob) : true if bob is null
- isNull(null) : true
Determines whether a value is null or empty.
True if:
- null; or
- it's a JObject and it's type is JTokenType.Null; or
- it's a JsonElement and it's ValueKind is JsonValueKind.Null; or
- it's a string and it's empty; or
- it's a JsonElement string and it's empty.
- value
- isNullOrEmpty(null) : true
- isNullOrEmpty('') : true
- isNullOrEmpty(' ') : false
- isNullOrEmpty(bob) : true if bob is null or whitespace
- isNullOrEmpty(1) : false
- isNullOrEmpty('text') : false
Determines whether a value is null, empty or whitespace.
Returns true is the value is:
- null; or
- it's a JObject and it's type is JTokenType.Null; or
- it's a JsonElement and it's ValueKind is JsonValueKind.Null; or
- it's a string and it's empty or only contains whitespace characters (\r, \n, \t, or ' '); or
- it's a JsonElement string and it's empty or only contains whitespace.
- value
- isNullOrWhiteSpace(null) : true
- isNullOrWhiteSpace('') : true
- isNullOrWhiteSpace(' ') : true
- isNullOrWhiteSpace(bob) : true if bob is null or whitespace
- isNullOrWhiteSpace(1) : false
- isNullOrWhiteSpace('text') : false
Determines whether a parameter is set.
- parameter name
- isSet('a') : true/false depending on whether a is an available variable
Determines the item at the given index. The first index is 0.
- parameter name
- itemAtIndex(split('a b c', ' '), 1) : 'b'
Creates a Newtonsoft JArray from input values.
- items[]
- jArray(jObject('a', 1, 'b', null), jObject('a', 2, 'b', #2024-06-21#)) : JArray [ { "a": 1, "b": null}, { "a": 2, "b": "2024-06-21T00:00:00"} ]
- jArray(1, null, 'woo') : JArray [ 1, null, "woo" ]
Creates a JObject from key/value pairs.
- key1 (string)
- value1
- key2 (string)
- value2
- ...
- keyN
- valueN
- jObject('a', 1, 'b', null) : JObject{ "a": 1, "b": null}
Creates a System.Text.Json JsonDocument array from input values.
- items[]
- jsonArray(1, 'test', null, true) : JsonDocument array containing [1, "test", null, true]
- jsonArray() : Empty JsonDocument array
- jsonArray(jsonDocument('a', 1), jsonDocument('b', 2)) : JsonDocument array containing two objects
Creates a System.Text.Json JsonDocument from key/value pairs.
- key1 (string)
- value1
- key2 (string)
- value2
- ...
- keyN
- valueN
- jsonDocument('a', 1, 'b', null) : JsonDocument with properties a=1 and b=null
Joins a list of strings into a single string.
- parameter name
- join(split('a b c', ' '), ', ') : 'a, b, c'
Selects a single value from a JObject using a JPath expression
- input JObject
- JPath string expression
sourceJObject JSON:
{
"name": "bob",
"details": {
"this.thing": "woo",
"that.thing": "yay",
},
"numbers": [ 1, 2 ],
"arrayList": [
{ "key": "key1", "value": "value1" },
{ "key": "key2", "value": "value2" }
]
}
- jPath(sourceJObject, 'name') : 'bob'
- jPath(sourceJObject, 'details.['this.thing']') : 'woo'
- jPath(sourceJObject, 'size') : an exception is thrown
- jPath(sourceJObject, 'size', True) : null is returned
- jPath(sourceJObject, 'numbers[0]') : 1
- jPath(sourceJObject, 'arrayList[?(@key==\'key1\')]') : "value1"
Returns the last item in a list that matches a lambda or throws a FormatException if no items match. Note that items are processed in reverse order.
- list
- predicate
- lambda expression as a string
- first(list(1, 5, 2, 3, 4, 1), 'n', 'n % 2 == 0') : 4
- first(list(1, 5, 7, 3), 'n', 'n % 2 == 0') : FormatException thrown
Determines the last position of a string within another string. Returns -1 if not present.
- longString
- shortString
- lastIndexOf('#abcabc#', 'abc') : 4
- lastIndexOf('#abcabc#', 'abcd') : -1
Returns the last item in a list that matches a lambda or null if no items match. Note that items are processed in reverse order.
- list
- predicate
- lambda expression as a string
- lastOrDefault(list(1, 5, 2, 3, 4, 1), 'n', 'n % 2 == 0') : 4
- lastOrDefault(list(1, 5, 7, 3), 'n', 'n % 2 == 0') : null
Determines length of a string or IList.
- string or IList
- length('a piece of string') : 17
- length(split('a piece of string', ' ')) : 4
Emits a List<object?> and collapses down lists of lists to a single list.
- the parameters
- list('', 1, '0')
- list(null, 1, '0')
- list(list(null, 1, '0'), 1, '0')
Emits a List<T>.
- the type
- the parameters
- listOf('object?', '', 1, '0')
- listOf('object?', null, 1, '0')
- listOf('int?', 1, null, 3)
- listOf('string', '1', '2', 3) : throws an exception
Emits the maximum value, ignoring nulls.
- the list
- optionally, a pair of parameters providing a lambda expression to be evaluated.
- max(listOf('int?', 1, null, 3)) : 3
- max(listOf('int', 1, 2, 3), 'x', 'x + 1') : 4
- max(listOf('string', '1', '2', '3')) : '3'
- max(listOf('string', '1', '2', '3'), 'x', 'x + x') : '33'
Emits the maximum possible value for a given numeric or date/time type.
- a string representing the type, which must be one of 'sbyte', 'byte', 'short', 'ushort', 'int', 'uint', 'long', 'ulong', 'float', 'double', 'decimal', 'DateTime', or 'DateTimeOffset'.
- maxValue('byte') : (byte)255
- maxValue('ushort') : (ushort)65535
- maxValue('int') : 2147483647
- maxValue('DateTime') : DateTime.MaxValue (9999-12-31T23:59:59.9999999)
- maxValue('DateTimeOffset') : DateTimeOffset.MaxValue (9999-12-31T23:59:59.9999999+00:00)
Emits the minimum value, ignoring nulls.
- the list
- optionally, a pair of parameters providing a lambda expression to be evaluated.
- min(listOf('int?', 1, null, 3)) : 1
- min(listOf('int', 1, 2, 3), 'x', 'x + 1') : 2
- min(listOf('string', '1', '2', '3')) : '1'
- min(listOf('string', '1', '2', '3'), 'x', 'x + x') : '11'
Emits the minimum possible value for a given numeric or date/time type.
- a string representing the type, which must be one of 'sbyte', 'byte', 'short', 'ushort', 'int', 'uint', 'long', 'ulong', 'float', 'double' 'decimal', 'DateTime', or 'DateTimeOffset'.
- minValue('byte') : (byte)0
- minValue('ushort') : (ushort)0
- minValue('int') : -2147483648
- minValue('DateTime') : DateTime.MinValue (0001-01-01T00:00:00.0000000)
- minValue('DateTimeOffset') : DateTimeOffset.MinValue (0001-01-01T00:00:00.0000000+00:00)
Returns the current date and time, with optional timezone correction.
- optionally, the name of a timezone
- now() : The current date and time in UTC
- now('UTC') : The current date and time in UTC
- now('Central European Standard Time') : The current date and time in Central Europe
Returns the first parameter that is not null, otherwise: null.
- any number of objects
- nullCoalesce() : null
- nullCoalesce(1, null) : 1
- nullCoalesce(null, 1, 2, 3) : 1
- nullCoalesce(null, null, null) : null
- nullCoalesce(null, null, 'xxx', 3) : 'xxx'
Orders an IEnumerable by one or more lambda expressions.
- list - the original list
- predicate - a string to represent the value to be evaluated
- nCalcString1 - the first orderBy lambda expression
- nCalcString2 (optional) - the next orderBy lambda expression
- nCalcString... (optional) - the next orderBy lambda expression
- orderBy(list(34, 33, 2, 1), 'n', 'n') : list(1, 2, 33, 34)
- orderBy(list(34, 33, 2, 1), 'n', '-n') : list(34, 33, 2, 1)
- orderBy(list(34, 33, 2, 1), 'n % 32', 'n % 2') : list(34, 33, 1, 2)
- orderBy(list(34, 33, 2, 1), 'n % 2', 'n % 32') : list(33, 1, 34, 2)
Pad the left of a string with a character to a desired string length.
- stringToPad
- desiredStringLength (must be >=1)
- paddingCharacter
- padLeft('', 1, '0') : '0'
- padLeft('12', 5, '0') : '00012'
- padLeft('12345', 5, '0') : '12345'
- padLeft('12345', 3, '0') : '12345'
Returns the conversion of a string to a numeric type. Supported types are:
- bool or System.Boolean
- sbyte or System.SByte
- byte or System.Byte
- short or System.Int16
- ushort or System.UInt16
- int or System.Int32
- uint or System.UInt32
- long or System.Int64
- ulong or System.UInt64
- double or System.Double
- float or System.Single
- decimal or System.Decimal
- JArray or Newtonsoft.Json.Linq.JArray (jArray also supported for backaward compatibility)
- JObject or Newtonsoft.Json.Linq.JObject (jObject also supported for backaward compatibility)
- JsonDocument or System.Text.Json.JsonDocument (jsonDocument also supported)
- JsonArray (for System.Text.Json arrays, jsonArray also supported)
- Guid
- type (see above)
- text
- valueIfParseFails (optional)
- parse('int', '1') : 1
- parse('System.Int32', '1') : 1
- parse('bool', 'x', null) : null
- parse('jObject', '{ "a" : 1 }', null) : JObject { "a": 1 }
- parse('jArray', '[ { "a" : 1 } ]', null) : JArray [{ "a": 1 }]
- parse('JsonDocument', '{ "a" : 1 }', null) : JsonDocument { "a": 1 }
- parse('JsonArray', '[ 1, 2, 3 ]', null) : JsonDocument array [1, 2, 3]
Returns an integer version of a string.
- integerAsString
- parseInt('1') : 1
Selects a regex group capture
- input
- regex
- zero-based capture index (default: 0)
- regexGroup('abcdef', '^ab(.+?)f$') : 'cde'
- regexGroup('abcdef', '^ab(.)+f$') : 'c'
- regexGroup('abcdef', '^ab(.)+f$', 1) : 'd'
- regexGroup('abcdef', '^ab(.)+f$', 2) : 'e'
- regexGroup('abcdef', '^ab(.)+f$', 10) : null
Determine whether a string matches a regex
- input
- regex
- regexIsMatch('abcdef', '^ab.+') : true
- regexIsMatch('Zbcdef', '^ab.+') : false
Replace a string with another string
- haystackString
- needleString
- betterNeedleString * ... (optional) more needle/betterNeedle pairs
- replace('abcdefg', 'cde', 'CDE') : 'abCDEfg'
- replace('abcdefg', 'cde', '') : 'abfg' * replace('abcdefg', 'a', '1', 'bc', '23') : '123defg'
Retrieves a value from storage
- key
- retrieve('thing')
Reverses an IEnumerable.
- list
- reverse(list(1, 2, 3, 4, 5, 5) : 5, 5, 4, 3, 2, 1
Sanitize a string, replacing any characters outside of the allowed set.
- input - the string to be sanitized
- allowedCharacters - all of the characters that are allowed
- replacementCharacters (optional) - the characters to insert in place of any that are not allowed (defaults : empty string)
- sanitize('ab cd', 'abcdefghi') : 'abcd'
- sanitize('ab cd./', 'abcdefghi.') : 'abcd.'
- sanitize('ab cd./', 'CBa') : 'a'
- sanitize('ab cd', 'abCD', '?') : 'ab???'
- sanitize('ab cd', 'ab', '?') : 'ab???'
- sanitize('ab cd', 'ab', '-') : 'ab---'
Converts an IEnumerable using a lambda.
- list - the original list
- predicate - a string to represent the value to be evaluated
- nCalcString - the value to evaluate to for each item in the list
- output list type - outputs a list of the specified type (optional)
- select(list(1, 2, 3, 4, 5), 'n', 'n + 1') : list(2, 3, 4, 5, 6)
- select(list(jObject('a', 1, 'b', '2'), jObject('a', 3, 'b', '4')), 'n', 'n', 'JObject') : list of JObjects
Converts an IEnumerable using a lambda and removes duplicates.
- list - the original list
- predicate - a string to represent the value to be evaluated
- nCalcString - the value to evaluate to for each item in the list
- selectDistinct(list(1, 2, 3, 3, 3), 'n', 'n + 1') : list(2, 3, 4)
Sets properties on an existing object.
- object - the original object
- property1 - the first new property name
- value1 - the first new property value
- propertyN (optional) - the nth new property name
- valueN (optional) - the nth new property value
- setProperties(jObject('a', 1, 'b', null), 'c', 'X') : jObject('a', 1, 'b', null, 'c', 'X')
- setProperties(jObject('a', 1, 'b', null), 'c', 'X', 'd', 'Y') : jObject('a', 1, 'b', null, 'c', 'X', 'd', 'Y')
Performs a SHA 256 hash of a string.
The output is a 64-character hexadecimal string.
- the input string
- sha('Hello'): '185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969'
Skips a number of items in a list.
If the number of items to skip is greater than the number of items in the list, an empty list is returned.
- the list to skip from
- the number of items to skip
- skip(list(1, 2, 3), 1): list(2, 3)
Sorts an IComparable ascending or descending.
- list - the original list
- direction (optional) - 'asc' is the default, 'desc' is the other option
- sort(list(2, 1, 3)) : list(1, 2, 3)
- sort(list(2, 1, 3), 'asc') : list(1, 2, 3)
- sort(list(2, 1, 3), 'desc') : list(3, 2, 1)
- sort(list('b', 'a', 'c'))) : list('a', 'b', 'c')
Splits a string on a given character into a list of strings.
- longString
- string to split on
- split('a bc d', ' ') : list('a', 'bc', 'd')
- split('aXXbcXXd', 'XX') : list('a', 'bc', 'd')
Determines whether a string starts with another string.
- longString
- shortString
- startsWith('abcdefg', 'ab') : true
- startsWith('abcdefg', 'cd') : false
Stores a value for use later in the pipeline
true
- key
- value
- store('thing', 1) : true
Retrieves part of a string. If more characters are requested than available at the end of the string, just the available characters are returned.
- inputString
- startIndex
- length (optional)
- substring('haystack', 3) : 'stack'
- substring('haystack', 0, 3) : 'hay'
- substring('haystack', 3, 100) : 'stack'
- substring('haystack', 0, 100) : 'haystack'
- substring('haystack', 0, 0) : ''
Sums numeric items. Optionally, perform a lambda on each one first.
- list - the original list
- predicate (optional) - a string to represent the value to be evaluated
- nCalcString (optional) - the string to evaluate
- sum(list(1, 2, 3)) : 6
- sum(list(1, 2, 3), 'n', 'n * n') : 14
Return one of a number of values, depending on the input function.
- switched value
- a set of pairs: case_n, output_n
- if present, a final value can be used as a default. If the default WOULD have been returned, but no default is present, an exception is thrown.
- switch('yes', 'yes', 1, 'no', 2) : 1
- switch('blah', 'yes', 1, 'no', 2) : throws exception
- switch('blah', 'yes', 1, 'no', 2, 3) : 3
Takes a number of items from a list.
If a number is provided that is longer than the list, the full list is returned.
- the list to take from
- the number of items to take
- take(list(1, 2, 3), 2): list(1, 2)
- take(list(1, 2, 3), 10): list(1, 2, 3)
Throws an NCalcExtensionsException. Useful in an if().
- message (optional)
- throw()
- throw('This is a message')
- if(problem, throw('There is a problem'), 5)
Determines the amount of time between two DateTimes. The following units are supported:
- Years
- Weeks
- Days
- Hours
- Minutes
- Seconds
- Milliseconds
- Any other string is handled with TimeSpan.ToString(timeUnit). See https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-timespan-format-strings
- startDateTime
- endDateTime
- timeUnit
- timeSpan('2019-01-01 00:01:00', '2019-01-01 00:02:00', 'seconds') : 3600
Converts a string to a UTC DateTime. May take an optional inputTimeZone.
When using numbers as the first input parameter, provide it as a decimal (see examples, below) to avoid hitting an NCalc bug relating to longs being interpreted as floats.
- inputString
- stringFormat
- inputTimeZone (optional) See https://docs.microsoft.com/en-us/dotnet/api/system.timezoneinfo.findsystemtimezonebyid?view=netstandard-2.0
- toDateTime('2019-01-01', 'yyyy-MM-dd') : A date time representing 2019-01-01
- toDateTime('2020-02-29 12:00', 'yyyy-MM-dd HH:mm', 'Eastern Standard Time') : A date time representing 2020-02-29 17:00:00 UTC
- toDateTime('2020-03-13 12:00', 'yyyy-MM-dd HH:mm', 'Eastern Standard Time') : A date time representing 2020-03-13 16:00:00 UTC
- toDateTime(161827200.0, 's', 'UTC') : A date time representing 1975-02-17 00:00:00 UTC
- toDateTime(156816000000.0, 'ms', 'UTC') : A date time representing 1974-12-21 00:00:00 UTC
- toDateTime(156816000000000.0, 'us', 'UTC') : A date time representing 1974-12-21 00:00:00 UTC
Converts a string to lower case.
- string
- toLower('PaNToMIMe') : 'pantomime'
Converts any object to a string
- object
- format (optional)
- toString(1) : '1'
- toString(1000, 'N2') : '1,000.00'
- toString(DateTimeOffset, 'yyyy-MM-dd') : '2023-02-17'
Converts a string to upper case.
- string
- toUpper('PaNToMIMe') : 'PANTOMIME'
Removes leading and trailing whitespace.
- string
- trim(' xxx xxx\n') : 'xxx xxx'
If a function throws an exception, return an alternate value.
- function to attempt
- result to return if an exception is thrown (null is returned if this parameter is omitted and an exception is thrown)
- try(1, 'Failed') : 1
- try(throw('Woo')) : null
- try(throw('Woo'), 'Failed') : 'Failed'
- try(throw('Woo'), exception_message) : 'Woo'
- try(throw('Woo'), exception_type) : typeof(PanoramicData.NCalcExtensions.Exceptions.NCalcExtensionsException)
- try(throw('Woo'), exception_typeFullName) : 'PanoramicData.NCalcExtensions.Exceptions.NCalcExtensionsException'
- try(throw('Woo'), exception_typeName) : 'NCalcExtensionsException'
- try(throw('Woo'), exception) : The Exception object thrown by the throw function.
Returns a boolean result of an attempted cast.
- type
- value
- key - for use with the retrieve() function
- tryParse('int', '1', 'outputVariable') : true
- tryParse('int', 'string', 'outputVariable') : false
Determines the C# type of the object.
- parameter
- typeOf('text') : 'String'
- typeOf(1) : 'Int32'
- typeOf(1.1) : 'Double'
- typeOf(null) : null
Filters an IEnumerable to bring back only those items that match a condition.
- list - the original list
- predicate - a string to represent the value to be evaluated
- nCalcString - the string to evaluate
- where(list(1, 2, 3, 4, 5), 'n', 'n < 3') : list(1, 2)
- where(list(1, 2, 3, 4, 5), 'n', 'n < 3 || n > 4') : list(1, 2, 5)