Skip to content

Instantly share code, notes, and snippets.

@ProbablePrime
Last active April 11, 2023 07:07
Show Gist options
  • Save ProbablePrime/819072e465d3d1acc2e5056f9d3d74ea to your computer and use it in GitHub Desktop.
Save ProbablePrime/819072e465d3d1acc2e5056f9d3d74ea to your computer and use it in GitHub Desktop.
A ReactiveUI question about summing properties from a collection based on a filter.
using DynamicData;
using DynamicData.Binding;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using System.Collections.ObjectModel;
using System.Diagnostics;
namespace ConsoleApp1;
/** Simplified for this question, but let's say I'm building a UI with this layout
* | Name | Should be Included| Size |
* | Record 1| [ ] |5 |
* | Record 2| [ ] |5 |
* ... etc.
*
* Total: the sum of items' size where their "Should be included" checkbox is true
*/
// For some boilerplate code here we go
// Our "Record" which has the properties from the table above
public class Record : ReactiveObject
{
public string Id { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
[Reactive]
public int Size { get; set; } = 0;
[Reactive]
public bool ShouldBeIncluded { get; set; } = false;
public Record(string id, string name, int size)
{
Id = id;
Name = name;
Size = size;
}
}
// A "View Model" that can be used to display them
public class Test
{
public ObservableCollection<Record> records;
// How do I keep Total up to date with the correct value, in this case 15?
[Reactive]
public int Total => records.Where(r => r.ShouldBeIncluded).Select(r => r.Size).Sum();
public Test()
{
records = new ObservableCollection<Record>();
//records.ToObservableChangeSet(x => x.Id).Filter(x=> x.ShouldBeIncluded). What's next? Is this right?;
}
}
public class Program
{
public static void Main(string[] args)
{
// Create a new test object
var t = new Test();
// Add 10 records to it, each with a size of 5
for (var i = 0; i < 10; i++)
{
t.records.Add(new Record(i.ToString(), $"Record {i}", 5));
}
// Mark 3 records as needing to be "Included"
t.records[0].ShouldBeIncluded = true;
t.records[3].ShouldBeIncluded = true;
t.records[5].ShouldBeIncluded = true;
Debug.Assert(t.Total == 15);
t.records[6].ShouldBeIncluded = true;
Debug.Assert(t.Total == 20);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment