奇怪的动态数据排序

Mik*_*yak 3 c# dynamic-data reactiveui

我认为 DynamicData 中的排序无法正常工作。可能是我不明白如何使用它?例子:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

结果很奇怪:第一个打印显示顺序是Hello2 Hello1,但第二个是——Hello1 Hello2。怎么了?

Rol*_*ant 8

当使用源缓存时,排序仅受绑定、页面和虚拟化操作符的尊重。这是出于性能原因,因为状态存储在没有排序概念的字典中。因此,您应该在绑定之前立即应用排序。

另一方面,对于源列表,状态存储在一个列表中,该列表了解由于被索引而导致的顺序。在这种情况下,排序可以应用于链上的任何地方。

  • “因此,您应该在绑定之前立即应用排序” - 一条超级关键的信息!被与此相关的错误困扰了将近一整天。 (3认同)