奇怪的动态数据排序

问题描述 投票:1回答:1

我认为DynamicData中的Sort不能正常工作。可能是我不知道如何使用?示例:

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();
        }
    }
}

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

c# dynamic-data reactiveui
1个回答
1
投票

使用源缓存时,排序仅受bind,page和virtualise运算符尊重。由于性能原因,因为状态存储在没有排序概念的字典中。因此,您应该在绑定之前立即应用排序。

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

© www.soinside.com 2019 - 2024. All rights reserved.