【问题标题】:How to Remove Duplicates from ICollectionView using FilterEventArgs MVVM如何使用 FilterEventArgs MVVM 从 ICollectionView 中删除重复项
【发布时间】:2020-09-27 16:00:32
【问题描述】:

我的Vehicle 模型中有两个属性:CategoryName

我有一个名为 VehiclesView 的 ICollectionView。

当绑定到Category 时,ListView 显示:

Airplane
Helicopter
Helicopter
Airplane
Car
Car

我必须能够过滤 VehiclesView 以删除相同 Category 的重复项,这将导致:

Airplane
Car
Helicopter

要求:过滤逻辑必须使用FilterEventArgs,像这样:

 public void ApplyFilter(object sender, FilterEventArgs e)
    {
        Vehicle v = e.Item as Vehicle;
        if (v != null)
        {
            // Remove duplicate instances of Category
            if (??????????????)
            {
                e.Accepted = false;
            }
            else
            {
                e.Accepted = true;
            }
        }
    }

我只需要过滤逻辑方面的帮助。

非常感谢任何帮助。

编辑 1:“类别”是用户定义的,这意味着过滤器必须在运行时比较属性值并删除重复项。

编辑 2:添加了所有已执行研究的链接,其中没有一个提供我需要的过滤逻辑,但确实提供了其他类型的过滤逻辑以及如何实现过滤/排序/分组的“大图”。

https://weblogs.asp.net/monikadyrda/wpf-listcollectionview-for-sorting-filtering-and-grouping

http://wpftutorial.net/DataViews.html

C# - how to get distinct items from a Collection View

https://social.technet.microsoft.com/wiki/contents/articles/26673.wpf-collectionview-tips.aspx

http://www.abhisheksur.com/2010/08/woring-with-icollectionviewsource-in.html

Implementing a ListView Filter with Josh Smith's WPF MVVM Demo App

http://www.codewrecks.com/blog/index.php/2011/02/23/filtering-in-mvvm-architecture/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+AlkampferEng+%28Alkampfer%27s+Place%29&utm_content=Google+Reader

【问题讨论】:

  • 是 WPF 吗? UWP?您使用的是哪个框架?另外,为什么要使用FilterEventArgs
  • @CorentinPane 感谢您的回复。我正在使用带有 MVVM 的 WPF。 FilterEventArgs 最适合我需要的解决方案。我已将您提供的链接设为红色,但它没有提供解决方案,因为在我的情况下 Category 是用户定义的。
  • @Andy 感谢安迪的回复。我已经阅读了那篇文章和其他几篇文章。他们提供了大局,这很棒,但他们没有解决我的问题。我只需要过滤逻辑来删除重复项。

标签: wpf mvvm filter duplicates icollectionview


【解决方案1】:

您可以创建一个查找表:

private HashSet<object> ExistingItemsTable { get; } = new HashSet<object>();
private void ApplyFilter(object sender, FilterEventArgs e)
{
  if (this.ExistingItemsTable.Contains(e.Item))
  {
    // FilterEventArgs.Accepted is true by default
    e.Accepted = false;
    return;
  }

  this.ExistingItemsTable.Add(e.Item);
}

您需要订阅源集合的CollectionChanged 事件来维护查找表:当项目被移除时,您还需要将它们从表中移除。

【讨论】:

  • 您可以只使用 HashSet 而不是字典。哈希集是开发人员相对很少遇到的东西,它“只是”键和识别已经见过的类别所需的一切。
  • @Andy 感谢您提出的改进建议。我已更新示例以替换 Dictionary
猜你喜欢
  • 2011-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多