Strange DynamicData sorting

1.5k views Asked by At

I think that Sort in DynamicData don't work properly. May be I don't understand how to use it? Example:

using DynamicData;
using DynamicData.Binding;
using ReactiveUI;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;

namespace DynamicDataTest
{
    public class Element:ReactiveObject
    {
        string name;
        public string Name { get => name; set => this.RaiseAndSetIfChanged(ref name,value); }
        int val;
        public int Value { get => val; set => this.RaiseAndSetIfChanged(ref val, value); }    
    }

    public class CollectionTest:ReactiveObject
    {
        public SourceCache<Element, int> source = new SourceCache<Element, int>(e => e.Value);
        public ReadOnlyObservableCollection<string> Info;
        public void Print()
        {
            Console.WriteLine("Begin print");
            foreach (var obj in Info) Console.WriteLine(obj);
            Console.WriteLine("End print");
        }
        public CollectionTest()
        {
            source.AddOrUpdate(new Element() { Name = "Hello1", Value = 4 });
            source.AddOrUpdate(new Element() { Name = "Hello2", Value = 3 });
            var connection = source.Connect().Sort(SortExpressionComparer<Element>.Ascending(e => e.Value));
            connection.Transform(t=>t.Name).Bind(out Info).Subscribe();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var test = new CollectionTest();
            test.Print();
            test.source.AddOrUpdate(new Element() { Name = "Hello1", Value = 4 });
            test.source.AddOrUpdate(new Element() { Name = "Hello2", Value = 3 });
            test.Print();
        }
    }
}

The result is strange: the first print show order Hello2 Hello1, but second -- Hello1 Hello2. What's wrong?

1

There are 1 answers

3
Roland Pheasant On

When using the source cache, sort is only respected by the bind, page and virtualise operator. This is for performance reasons as the state is stored in a dictionary which has no concept of ordering. Therefore you should apply the sort immediately before Bind.

On the other hand, for source list the state is store in a list which understands the order due to it being indexed. In this case sort can be applied anywhere along the chain.