Skip to content
Skills Library
Programming · Building & coding

dynamic-data

/dynamic-data

USE FOR: Reactive collection management using observable caches and lists with LINQ-style operators for filtering, sorting, grouping, transforming, and binding to UI collections. DO NOT USE FOR: Simple ObservableCollection scenarios, non-reactive LINQ queries, or server-side data access (use Entity Framework or Dapper).

Licence
MIT
Last repository change
09.06.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
20
Scripts
0
HTML comments
0
URLs in SKILL.md
2
Deprecation

No signals detected. Repository changed on 09.06.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

USE FOR: Reactive collection management using observable caches and lists with LINQ-style operators for filtering, sorting, grouping, transforming, and binding to UI collections. DO NOT USE FOR: Simple ObservableCollection scenarios, non-reactive LINQ queries, or server-side data access (use Entity Framework or Dapper).

Original author description

USE FOR: Reactive collection management using observable caches and lists with LINQ-style operators for filtering, sorting, grouping, transforming, and binding to UI collections. DO NOT USE FOR: Simple ObservableCollection scenarios, non-reactive LINQ queries, or server-side data access (use Entity Framework or Dapper).

How it works

  1. Overview
  2. Installation
  3. SourceCache: Keyed Collections
  4. SourceList: Ordered Collections
  5. Reactive Filtering with Dynamic Predicates
  6. Grouping
  7. Key Operators Reference
  8. Best Practices
Original SKILL.md headings · 283 lines, 1,151 words
SKILL.md preview
---
name: dynamic-data
description: >
  USE FOR: Reactive collection management using observable caches and lists with LINQ-style
  operators for filtering, sorting, grouping, transforming, and binding to UI collections.
  DO NOT USE FOR: Simple ObservableCollection scenarios, non-reactive LINQ queries, or
  server-side data access (use Entity Framework or Dapper).
license: MIT
metadata:
  displayName: DynamicData
  author: "Tyler-R-Kendrick"
  version: "1.0.0"
compatibility:
  - claude
  - copilot
  - cursor
references:
  - title: "DynamicData GitHub Repository"
    url: "https://github.com/reactivemarbles/DynamicData"
  - title: "DynamicData NuGet Package"
    url: "https://www.nuget.org/packages/DynamicData"
---

# DynamicData

## Overview

DynamicData is a reactive collections library built on top of Reactive Extensions (Rx). It provides `SourceCache<TObject, TKey>` and `SourceList<T>` as mutable data sources, and a rich set of LINQ-style operators (`Filter`, `Sort`, `Transform`, `Group`, `Bind`) that produce observable change sets. When items are added, removed, or updated in the source, operators propagate only the changes (not the entire collection) downstream, making UI binding highly efficient.

DynamicData is commonly used with ReactiveUI for MVVM applications in WPF, MAUI, Avalonia, and Blazor, but it works independently of any UI framework.

## Installation

```bash
dotnet add package DynamicData
```

## SourceCache: Keyed Collections

`SourceCache<TObject, TKey>` manages a collection of items identified by a unique key. All modifications go through the cache, and downstream operators receive granular change sets.

```csharp
using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using DynamicData;
using DynamicData.Binding;

namespace MyApp.ViewModels;

public record Employee(int Id, string Name, string Department, decimal Salary, bool IsActive);

public class EmployeeListViewModel : IDisposable
{
    private readonly SourceCache<Employee, int> _cache;
    private readonly CompositeDisposable _disposables = new();

    public IObservableCollection<EmployeeViewModel> ActiveEmployees { get; }
    public IObservableCollection<EmployeeViewModel> AllEmployees { get; }

    public EmployeeListViewModel()
    {
        _cache = new SourceCache<Employee, int>(e => e.Id);

        // Filter to active employees, transform to view models, sort, and bind
        ActiveEmployees = new ObservableCollectionExtended<EmployeeViewModel>();
        _cache.Connect()
            .Filter(e => e.IsActive)
            .Transform(e => new EmployeeViewModel(e))
            .Sort(SortExpressionComparer<EmployeeViewModel>
                .Ascending(vm => vm.Name))
            .ObserveOn(RxApp.MainThreadScheduler)
            .Bind((IObservableCollection<EmployeeViewModel>)ActiveEmployees)
            .Subscribe()
            .DisposeWith(_disposables);

        // All employees without filter
        AllEmployees = new ObservableCollectionExtended<EmployeeViewModel>();
        _cache.Connect()
            .Transform(e => new EmployeeViewModel(e))
            .Sort(SortExpressionComparer<EmployeeViewModel>
                .Ascending(vm => vm.Department)
                .ThenByAscending(vm => vm.Name))
            .ObserveOn(RxApp.MainThreadScheduler)
            .Bind((IObservableCollection<EmployeeViewModel>)AllEmployees)
            .Subscribe()
            .DisposeWith(_disposables);
    }

    public void AddEmployee(Employee employee) =>
        _cache.AddOrUpdate(employee);

    public void RemoveEmployee(int id) =>
        _cache.RemoveKey(id);

    public void BulkLoad(IEnumerable<Employee> employees) =>
        _cache.Edit(innerCache =>
        {
            innerCache.Clear();
            innerCache.AddOrUpdate(employees);
        });

    public void Dispose() => _disposables.Dispose();
}

public record EmployeeViewModel(Employee Employee)
{
    public string Name => Employee.Name;
    public string Department => Employee.Department;
    public decimal Salary => Employee.Salary;
}
```

## SourceList: Ordered Collections

`SourceList<T>` is for collections where items do not have a natural key and ordering matters.

```csharp
using System;
using System.Reactive.Disposables;
using DynamicData;
using DynamicData.Binding;

namespace MyApp.ViewModels;

public record LogEntry(DateTime Timestamp, string Level, string Message);

public class LogViewerViewModel : IDisposable
{
    private readonly SourceList<LogEntry> _logs = new();
    private readonly CompositeDisposable _disposables = new();

    public IObservableCollection<LogEntry> FilteredLogs { get; }

    public LogViewerViewModel(string levelFilter = "Error")
    {
        FilteredLogs = new ObservableCollectionExtended<LogEntry>();

        _logs.Connect()
            .Filter(log => log.Level == levelFilter)
            .Sort(SortExpressionComparer<LogEntry>
                .Descending(l => l.Timestamp))
            .Top(100)  // Keep only the 100 most recent
            .Bind((IObservableCollection<LogEntry>)FilteredLogs)
            .Subscribe()
            .DisposeWith(_disposables);
    }

    public void AddLog(LogEntry entry) => _logs.Add(entry);

    public void Clear() => _logs.Clear();

    public void Dispose() => _disposables.Dispose();
}
```

## Reactive Filtering with Dynamic Predicates

Filters can react to changing predicates using `IObservable<Func<T, bool>>`.

```csharp
using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using DynamicData;
using DynamicData.Binding;

namespace MyApp.ViewModels;

public record Product(int Id, string Name, string Category, decimal Price);

public class ProductSearchViewModel : IDisposable
{
    private readonly SourceCache<Product, int> _cache;
    private readonly BehaviorSubject<string> _searchTerm = new(string.Empty);
    private readonly BehaviorSubject<string> _categoryFilter = new("All");
    private readonly CompositeDisposable _disposables = new();

    public IObservableCollection<Product> Results { get; }

    public string SearchTerm
    {
        get => _searchTerm.Value;
        set => _searchTerm.OnNext(value);
    }

    public string CategoryFilter
    {
        get => _categoryFilter.Value;
        set => _categoryFilter.OnNext(value);
    }

    public ProductSearchViewModel()
    {
        _cache = new SourceCache<Product, int>(p => p.Id);
        Results = new ObservableCollectionExtended<Product>();

        // Combine search term and category filter into a dynamic predicate
        var dynamicFilter = _searchTerm
            .Throttle(TimeSpan.FromMilliseconds(300))
            .CombineLatest(_categoryFilter, (search, category) =>
            {
                return new Func<Product, bool>(product =>
                {
                    bool matchesSearch = string.IsNullOrEmpty(search) ||
                        product.Name.Contains(search, StringComparison.OrdinalIgnoreCase);
                    bool matchesCategory = category == "All" ||
                        product.Category == category;
                    return matchesSearch && matchesCategory;
                });
            });

        _cache.Connect()
            .Filter(dynamicFilter)
            .Sort(SortExpressionComparer<Product>.Ascending(p => p.Name))
            .Bind((IObservableCollection<Product>)Results)
            .Subscribe()
            .DisposeWith(_disposables);
    }

    public void LoadProducts(IEnumerable<Product> products) =>
        _cache.AddOrUpdate(products);

    public void Dispose()
    {
        _searchTerm.Dispose();
        _categoryFilter.Dispose();
        _disposables.Dispose();
    }
}
```

## Grouping

```csharp
using System;
using System.Reactive.Disposables;
using DynamicData;
using DynamicData.Binding;

namespace MyApp.ViewModels;

public class GroupedEmployeeViewModel : IDisposable
{
    private readonly SourceCache<Employee, int> _cache;
    private readonly CompositeDisposable _disposables = new();

    public IObservableCollection<IGroup<Employee, int, string>> Departments { get; }

    public GroupedEmployeeViewModel()
    {
        _cache = new SourceCache<Employee, int>(e => e.Id);
        Departments = new ObservableCollectionExtended<IGroup<Employee, int, string>>();

        _cache.Connect()
            .Group(e => e.Department)
            .Bind((IObservableCollection<IGroup<Employee, int, string>>)Departments)
            .Subscribe()
            .DisposeWith(_disposables);
    }

    public void Dispose() => _disposables.Dispose();
}
```

## Key Operators Reference

| Operator               | Source Type    | Purpose                                           |
|------------------------|---------------|---------------------------------------------------|
| `Filter`               | Cache / List  | Include items matching a predicate                |
| `Transform`            | Cache / List  | Project each item to a new type                   |
| `Sort`                 | Cache / List  | Order items by one or more expressions            |
| `Bind`                 | Cache / List  | Bind change set to an `IObservableCollection`     |
| `Group`                | Cache         | Group items by a key selector                     |
| `Top`                  | Cache / List  | Take the first N items after sorting              |
| `DistinctValues`       | Cache         | Extract distinct values of a property             |
| `MergeMany`            | Cache         | Merge observables from each item into one stream  |
| `AutoRefresh`          | Cache         | Re-evaluate operators when a property changes     |
| `TransformMany`        | Cache         | Flatten one-to-many relationships                 |
| `Except`               | Cache         | Items in source but not in another cache          |
| `And` / `Or`           | Cache         | Set operations between two caches                 |

## Best Practices

1. **Use `SourceCache<TObject, TKey>` for collections with a natural unique key (database IDs, GUIDs)** and `SourceList<T>` for ordered collections without keys, because the cache provides O(1) lookup and deduplication.

2. **Call `.DisposeWith(disposables)` on every subscription and dispose the `CompositeDisposable` in the view model's `Dispose` method** to prevent memory leaks from long-lived subscriptions that hold references to the source cache.

3. **Use `cache.Edit(innerCache => { ... })` for bulk mutations** to batch multiple adds, removes, and updates into a single change set notification, preventing N separate UI updates when loading N items.

4. **Apply `ObserveOn(RxApp.MainThreadScheduler)` before `.Bind()`** to marshal change set notifications to the UI thread; binding on a background thread causes cross-thread access exceptions in WPF, MAUI, and WinUI.

5. **Use `SortExpressionComparer<T>.Ascending(x => x.Property)` instead of custom `IComparer<T>` implementations** because the expression-based comparer integrates with DynamicData's change-tracking and produces correct incremental sort updates.

6. **Use `AutoRefresh(e => e.PropertyName)` when items implement `INotifyPropertyChanged` and a filter or sort depends on a mutable property** so that the operator re-evaluates when the property changes, not only when items are added or removed.

7. **Throttle dynamic filter predicates with `.Throttle(TimeSpan.FromMilliseconds(300))`** when the predicate changes on every keystroke (search boxes) to avoid re-filtering the entire cache on every character typed.

8. **Prefer `Transform` over `Select`** because `Transform` produces a change set that tracks the relationship between source and transformed items, enabling efficient removal of transformed items when the source item is removed.

9. **Use `DistinctValues(e => e.Category)` to extract unique property values for filter dropdowns** rather than manually tracking categories, so the dropdown automatically updates when items with new categories are added.

10. **Keep the `SourceCache` as a private field in the view model and expose only `IObservableCollection<T>` to the view** to enforce unidirectional data flow where mutations go through view model methods and the UI only reads the bound collection.
Files in this package (20)
  • AGENTS.md 11 KB
  • README.md 1 KB
  • SKILL.md 12 KB
  • metadata.json 1 KB
  • rules/_sections.md 3 KB
  • rules/_template.md 1 KB
  • rules/dynamic-data-apply-observeon-rxapp-mainthreadscheduler-before-bind.md 1 KB
  • rules/dynamic-data-call-disposewith-disposables-on-every-subscription-and.md 1 KB
  • rules/dynamic-data-combine-with-reactiveui.md 1 KB
  • rules/dynamic-data-dispose-subscriptions-properly.md 1 KB
  • rules/dynamic-data-keep-the-sourcecache-as-a-private-field-in-the-view-model.md 1 KB
  • rules/dynamic-data-prefer-transform-over-select.md 1 KB
  • rules/dynamic-data-throttle-dynamic-filter-predicates-with-throttle-timespan.md 1 KB
  • rules/dynamic-data-use-appropriate-operators.md 1 KB
  • rules/dynamic-data-use-autorefresh-e-e-propertyname-when-items-implement.md 1 KB
  • rules/dynamic-data-use-cache-edit-innercache-for-bulk-mutations.md 1 KB
  • rules/dynamic-data-use-distinctvalues-e-e-category-to-extract-unique-property.md 1 KB
  • rules/dynamic-data-use-for-reactive-collections.md 1 KB
  • rules/dynamic-data-use-sortexpressioncomparer-t-ascending-x-x-property-instead.md 1 KB
  • rules/dynamic-data-use-sourcecache-tobject-tkey-for-collections-with-a-natural.md 1 KB

Versions

The database has no other skills named dynamic-data.

Database snapshot: 13.11.2026 · package version 64c8c17b33cf (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 95entity-framework-core
    Entity Framework Core with DbContext, migrations, LINQ queries, relationships, and performance optimization. Covers EF Core 8+ patterns. USE WHEN: user mentions "Entity Framework", "EF Core", "DbContext", "migrations", "LINQ", "EF relationships", "database first", "code first"…
  • 100entity-framework-core
    USE FOR: CRUD data access with LINQ, database migrations, change tracking, complex domain models with relationships, database-first and code-first workflows, and multi-provider support (SQL Server, PostgreSQL, SQLite, Cosmos DB). DO NOT USE FOR: Bulk operations on millions of…
  • 90csharp-linq
    Use LINQ with deferred execution understood, database translation respected, and loops chosen when they win. Use when writing C# queries over collections or ORMs, or debugging surprising LINQ behavior.
  • 100reactive-extensions
    USE FOR: Composing event streams, UI events, timers, and asynchronous data sources using IObservable<T> with LINQ operators for filtering, throttling, combining, and error handling. DO NOT USE FOR: Simple async/await workflows, pull-based data streaming (use IAsyncEnumerable),…
  • 91csharp-linq
    Use when lINQ query and method syntax, deferred execution, and performance optimization. Use when querying collections in C#.
  • 90neo-dotnet-ef-core
    Use this skill when the task involves Entity Framework Core models, DbContext, migrations, LINQ queries, change tracking, database providers, performance tuning, or data access review in .NET projects.

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.