【问题标题】:Strange DynamicData sorting奇怪的动态数据排序
【发布时间】:2020-03-11 08:14:19
【问题描述】:

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

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

【问题讨论】:

  • this 有帮助吗?如果我理解正确,AddOrUpdate 实际上并没有更新,这就是 SourceCache 不再排序的原因。

标签: c# dynamic-data reactiveui


【解决方案1】:

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

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

【讨论】:

  • 我不明白你的回答。我不能在绑定之前立即排序,因为排序键不是绑定集合的一部分。我按值排序并绑定到字符串集合。转换是必要的,
  • 我表达了源缓存的限制,这是设计使然。您的选择是转换为包含排序键的对象,视图模型或值元组。或者使用源列表。
  • “因此,您应该在 Bind 之前立即应用排序” - 一条超级关键的信息!被一个与此相关的错误困住了将近一整天。
猜你喜欢
  • 2013-01-09
  • 2014-11-08
  • 1970-01-01
  • 1970-01-01
  • 2011-03-13
  • 2015-09-08
  • 1970-01-01
  • 2012-12-17
  • 1970-01-01
相关资源
最近更新 更多