C#-如何从集合视图中获取不同的项目 [英] C# - how to get distinct items from a Collection View
问题描述
CollectionView view = CollectionView)CollectionViewSource.GetDefaultView(MyData);
View.Filter = i => ((MyClass)i).MyProperty;
我有一个像上面一样的集合视图.问题是已经绑定到列表视图的MyData集合包含重复项.过滤后如何获得唯一的商品?
I have a collection view like in the above. The problem is that the collection MyData which has already been bound to a listview contains duplicate items. How do I get unique items as the result of my filtering?
推荐答案
此方法有效:
CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView(c.Items);
view.Filter = i =>
{
var index1 = c.MyData.FindIndex(delegate (MyClass s)
{
return Object.ReferenceEquals(s, i);
});
var index2 = c.MyData.FindLastIndex(delegate (MyClass s)
{
return ((MyClass)i).MyProperty == s.MyProperty as string; //value comparison
});
return index1 == index2;
};
index1
是对象在集合中的索引.您需要比较引用
来获得.
index1
is the index of the object in the collection. You need to compare the references
to get that.
index2
是 value
的最后一个索引.在那里,您需要比较 value
.
index2
is the last index of the value
. There you need to compare the value
.
因此,您基本上可以比较当前 element
的 index
是否是它出现的最后一个索引.
So you basically compare if the index
of the current element
is the last one where it occurs.
注意:
这不适用于简单类型.我必须像这样初始化我的测试集合:
this does not work naturally with simple types. I had to initialize my test collection like this:
新列表< string>(){新字符串("I1" .ToCharArray()),新字符串("I1" .ToCharArray()),"I2"};
这篇关于C#-如何从集合视图中获取不同的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!