Epiforge.Extensions.Expressions
3.0.1
See the version list below for details.
dotnet add package Epiforge.Extensions.Expressions --version 3.0.1
NuGet\Install-Package Epiforge.Extensions.Expressions -Version 3.0.1
<PackageReference Include="Epiforge.Extensions.Expressions" Version="3.0.1" />
<PackageVersion Include="Epiforge.Extensions.Expressions" Version="3.0.1" />
<PackageReference Include="Epiforge.Extensions.Expressions" />
paket add Epiforge.Extensions.Expressions --version 3.0.1
#r "nuget: Epiforge.Extensions.Expressions, 3.0.1"
#:package Epiforge.Extensions.Expressions@3.0.1
#addin nuget:?package=Epiforge.Extensions.Expressions&version=3.0.1
#tool nuget:?package=Epiforge.Extensions.Expressions&version=3.0.1
This library has useful tools for dealing with expressions:
ExpressionEqualityComparer- Defines methods to support the comparison of expression trees for equalityExpressionExtensions, providing:Duplicate- Duplicates the specified expression treeSubstituteMethods- Recursively scans an expression tree to replace invocations of specific methods with replacement methods
Observable
This library accepts a LambdaExpression and arguments to pass to it, dissects the LambdaExpression's body, and hooks into change notification events for properties (INotifyPropertyChanged), collections (INotifyCollectionChanged), and dictionaries (Epiforge.Extensions.Collections.INotifyDictionaryChanged).
// Employee implements INotifyPropertyChanged
var elizabeth = Employee.GetByName("Elizabeth");
var observer = new ExpressionObserver();
var expr = observer.Observe(e => e.Name.Length, elizabeth);
// expr subscribed to elizabeth's PropertyChanged
Then, as changes involving any elements of the expression occur, a chain of automatic re-evaluation will get kicked off, possibly causing the observable expression's Evaluation property to change.
var elizabeth = Employee.GetByName("Elizabeth");
var observer = new ExpressionObserver();
var expr = observer.Observe(e => e.Name.Length, elizabeth);
// expr.Evaluation.Result == 9
elizabeth.Name = "Lizzy";
// expr.Evaluation.Result == 5
Also, since exceptions may be encountered after an observable expression was created due to subsequent element changes, observable expressions include a Fault property in their evaluations, which will be set to the exception that was encountered during evaluation.
var elizabeth = Employee.GetByName("Elizabeth");
var observer = new ExpressionObserver();
var expr = observer.Observe(e => e.Name.Length, elizabeth);
// expr.Evaluation.Fault is null
elizabeth.Name = null;
// expr.Evaluation.Fault is NullReferenceException
Observable expressions raise property change events of their own, so listen for those (kinda the whole point)!
var elizabeth = Employee.GetByName("Elizabeth");
var observer = new ExpressionObserver();
var expr = observer.Observe(e => e.Name.Length, elizabeth);
expr.PropertyChanged += (sender, e) =>
{
if (e.PropertyName == "Evaluation")
{
var (fault, result) = expr.Evaluation;
if (fault is not null)
{
// Whoops
}
else
{
// Do something with result
}
}
};
When you dispose of your observable expression, it will disconnect from all the events.
var elizabeth = Employee.GetByName("Elizabeth");
var observer = new ExpressionObserver();
using (var expr = observer.Observe(e => e.Name.Length, elizabeth))
{
// expr subscribed to elizabeth's PropertyChanged
}
// expr unsubcribed from elizabeth's PropertyChanged
Observable expressions will also try to automatically dispose of disposable objects they create in the course of their evaluation when and where it makes sense. Use the ExpressionObserverOptions class for more direct control over this behavior.
You can use the Optimizer property to specify an optimization method to invoke automatically during the observable expression creation process.
We recommend Tuomas Hietanen's Linq.Expression.Optimizer, the utilization of which would look like so:
var options = new ExpressionObserverOptions { Optimizer = ExpressionOptimizer.tryVisit };
var a = Expression.Parameter(typeof(bool));
var b = Expression.Parameter(typeof(bool));
var lambda = Expression.Lambda<Func<bool, bool, bool>>
(
Expression.AndAlso
(
Expression.Not(a),
Expression.Not(b)
),
a,
b
); // lambda explicitly defined as (a, b) => !a && !b
var observer = new ExpressionObserver(options);
var expr = observer.Observe<bool>(lambda, false, false);
// optimizer has intervened and defined expr as (a, b) => !(a || b)
// (because Augustus De Morgan said they're essentially the same thing, but this involves less steps)
Observable Queries
This library provides re-implementations of LINQ operations, but instead of returning IEnumerable<T>s and simple values, these return IObservableCollectionQuery<T>s, IObservableDictionaryQuery<TKey, TValue>s, and IObservableScalarQuery<T>s.
This is because, unlike traditional LINQ operations, these implementations continuously update their results until those results are disposed.
What they hand back is a read-only view of the source: change the source, and the query brings itself up to date. Queries do not implement the mutating range collection and dictionary interfaces, because a query result is not somewhere you put things.
But... what could cause those updates?
- the source is enumerable, implements
INotifyCollectionChanged, and raises aCollectionChangedevent - the source is a dictionary, implements
Epiforge.Extensions.Collections.INotifyDictionaryChanged<TKey, TValue>, and raises aDictionaryChangedevent - the elements in the enumerable (or the values in the dictionary) implement
INotifyPropertyChangedand raise aPropertyChangedevent - a reference enclosed by a selector or a predicate passed to the method implements
INotifyCollectionChanged,Epiforge.Extensions.Collections.INotifyDictionaryChanged<TKey, TValue>, orINotifyPropertyChangedand raises one of their events
That last one might be a little surprising, but this is because all selectors and predicates passed to Observable Query methods become Observable Expressions (see above).
This means that you will not be able to pass one that an ExpressionObserver cannot observe (e.g. a lambda expression that can't be converted to an expression tree or that contains nodes that are unsupported).
But, in exchange for this, you get all kinds of notification plumbing that's just handled for you behind the scenes.
Suppose, for example, you're working on an app that displays a list of notes and you want the notes to be shown in descending order of when they were last edited.
var notes = new ObservableCollection<Note>();
var collectionObserver = new CollectionObserver();
var observedNotes = collectionObserver.ObserveReadOnlyList(notes);
var orderedNotes = observedNotes.ObserveOrderBy(note => note.LastEdited, isDescending: true);
notesViewControl.ItemsSource = orderedNotes;
From then on, as you add Notes to the notes observable collection, the IObservableCollectionQuery<Note> named orderedNotes will be kept ordered so that notesViewControl displays them in the preferred order.
Since IObservableCollectionQuery<T>'s are automatically subscribing to events for you, you do need to call Dispose on them when you don't need them any more.
void Page_Unload(object? sender, EventArgs e)
{
orderedNotes.Dispose();
observedNotes.Dispose();
}
Ahh, but what about exceptions?
Well, Observable Expressions contain a Fault element in their Evaluation properties, but... you don't really see those Observable Expressions as an Observable Query caller, do ya?
For that reason, Observable Queries all have OperationFault properties.
You may subscribe to their PropertyChanging and PropertyChanged events to be notified when an Observable Expression or the overall Observable Query runs into a problem.
If there is more than one fault in play, the value of OperationFault will be an AggregateException.
Dictionary queries adopt the key comparer of the dictionary they observe, discovering it through Epiforge.Extensions.Collections.Generic.IHashKeys<TKey> or a Dictionary<TKey, TValue>'s own Comparer, so a query over a case-insensitive dictionary is itself case-insensitive.
ObserveGroupBy, ObserveToLookup, and ObserveDistinct do not order their results the way LINQ does.
Groupings are ordered by when they were created and the elements of a grouping by when they were added, rather than by where they occur in the source.
This is deliberate: holding a grouping at the position of its key's first occurrence would mean moving that grouping every time an element was inserted ahead of it, announcing a change to something whose membership did not change, which is the opposite of what an Observable Query is for.
Call ObserveOrderBy on the query, or on a grouping, when you want a defined order.
Reach for foreach rather than the indexer, because the difference between them is larger than it looks and grows with the collection.
An enumeration takes the query's lock once and then walks a list, while the indexer takes that lock again for every element you ask for; on a large collection it must also find each one in a tree, because a query keeps its elements' positions in one so that a change repairs only what it touched.
A query does remember the position it handed out last and searches outward from there, so asking for positions in order, or near one another, costs a fraction of asking for them at random, and what remains is mostly the repeated locking rather than the search.
Walking ten thousand elements by index instead of by enumerator measured between thirty and fifty times slower in order, and around two hundred times out of order; at a hundred elements it was about fifteen, and there the repeated locking is the whole of it.
Where you do need elements by position more than once, copy the query's contents and index the copy.
Since the ExpressionObserver has a number of options governing its behavior, you may optionally pass one you've made to the constructor of CollectionObserver to ensure those options are obeyed when Observable Expressions are created to enable your Observable Queries.
How Observable Queries Work and When to Use Them
It is worth being plain about what kind of thing this is, because "LINQ, but observable" undersells it and sets the wrong expectations.
A LINQ query is a description of a computation you run. Run it again and it does all of the work again. An Observable Query is not re-run. It is a small machine that holds the answer and repairs it, so when something changes, only the parts of the answer that depended on that thing are recomputed. The work is proportional to what changed rather than to how much data you have. If you want the name the literature uses for this idea, it is incremental, or self-adjusting, computation.
Three things that might otherwise look like arbitrary restrictions fall straight out of that:
- Your selectors and predicates have to be expression trees rather than delegates because the machine has to read them to find out what they depend on. A delegate is opaque; there is nothing in it to subscribe to.
- You have to dispose of a query because it is holding subscriptions to everything it depends on, and those subscriptions are the entire reason the answer stays right.
- Faults reach you through
OperationFaultinstead of being thrown, because the evaluation that failed happened later, on whatever thread raised the change. By then there is no call of yours left on the stack to throw out of.
What is not free is construction. Building the machine means building an observable expression for every element the query touches, and that is proportional to the size of the collection. So build a query once and hold onto it. Do not build one per frame, per request, or per keystroke. The bargain is that you pay up front and then stop paying to read.
Which is also how to decide whether you want one. If you compute a result once and move on, plain LINQ is cheaper and simpler, and you should use it. If a result has to stay correct across a long run of small changes, such as a list someone is looking at, a running total, or a filter someone is typing into, that is what these are for.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 is compatible. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Epiforge.Extensions.Collections (>= 3.1.0)
- Epiforge.Extensions.Components (>= 4.1.0)
-
net6.0
- Epiforge.Extensions.Collections (>= 3.1.0)
- Epiforge.Extensions.Components (>= 4.1.0)
- System.Collections.Immutable (>= 8.0.0)
-
net7.0
- Epiforge.Extensions.Collections (>= 3.1.0)
- Epiforge.Extensions.Components (>= 4.1.0)
- System.Collections.Immutable (>= 8.0.0)
-
net8.0
- Epiforge.Extensions.Collections (>= 3.1.0)
- Epiforge.Extensions.Components (>= 4.1.0)
-
net9.0
- Epiforge.Extensions.Collections (>= 3.1.0)
- Epiforge.Extensions.Components (>= 4.1.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 4.2.0 | 39 | 8/31/2026 |
| 4.1.0 | 40 | 8/31/2026 |
| 4.0.0 | 95 | 8/30/2026 |
| 3.0.1 | 81 | 8/29/2026 |
| 3.0.0 | 170 | 8/27/2026 |
| 2.3.8 | 217 | 6/6/2026 |
| 2.3.7 | 119 | 6/6/2026 |
| 2.3.6 | 125 | 6/6/2026 |
| 2.3.5 | 117 | 6/3/2026 |
| 2.3.4 | 122 | 5/31/2026 |
| 2.3.3 | 118 | 5/29/2026 |
| 2.3.2 | 129 | 5/8/2026 |
| 2.3.1 | 119 | 5/7/2026 |
| 2.3.0 | 119 | 5/7/2026 |
| 2.2.0 | 129 | 4/23/2026 |
| 2.1.2 | 129 | 4/14/2026 |
| 2.1.1 | 139 | 4/12/2026 |
| 2.1.0 | 124 | 4/5/2026 |
| 2.0.2 | 255 | 12/24/2025 |
| 2.0.1 | 738 | 12/1/2025 |
Corrected: a member expression observing a collection or dictionary held in a field of a compiler-generated type announced the change to nothing, so an expression closing over such a collection stopped re-evaluating when its contents changed. This affected the default configuration.
Observable expression nodes no longer notify of property changes internally, carry a finalizer, or hold a lock for their deferred-evaluation flag, and no longer track a sequence for the dependents they notify. A node is roughly seventy bytes lighter, and a change to a value that a thousand expressions depend on propagates in a little over half the time it did.
Reading Keys or Values, and enumerating, no longer copy the whole result on every call for the group-by, individual-changes, lookup, to-dictionary, dictionary select, and dictionary where queries; the copy is made once and discarded when the result changes, as it already was for the others. On a ten thousand entry dictionary query, reading Values now allocates nothing and returns in about twelve nanoseconds rather than twenty microseconds.