Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtered CollectionView Gives Wrong Count

According to the documentation, the Count of a filtered CollectionView should only be the count of items that pass the filter. Given this code:

List<string> testList = new List<string>();
testList.Add("One");
testList.Add("Two");
testList.Add("Three");
testList.Add("1-One");
testList.Add("1-Two");
testList.Add("1-Three");
CollectionView testView = new CollectionView(testList);
int testCount1 = testView.Count;
testView.Filter = (i) => i.ToString().StartsWith("1-");
int testCount2 = testView.Count;

I would therefore expect testCount1 to be 6, and testCount2 to be 3. However, both are 6. If I manually iterate through the CollectionView and count the items, I do get 3, but Count returns 6 always.

I've tried calling Refresh on the CollectionView, just to see if that would correct the result, but there was no change. Is the documentation wrong? Is there a bug in CollectionView? Am I doing something wrong that I just can't see?

like image 514
David Mullin Avatar asked Apr 11 '11 15:04

David Mullin


2 Answers

Try

ICollectionView _cvs = CollectionViewSource.GetDefaultView(testList);

instead of

CollectionView testView = new CollectionView(testList);    
like image 175
Bruno Avatar answered Nov 05 '22 10:11

Bruno


If you switch to ListCollectionView, then it works as expected:

CollectionView testView = new ListCollectionView(testList);
int testCount1 = testView.Count;
testView.Filter = (i) => i.ToString().StartsWith("1-");
int testCount2 = testView.Count;

This seems to work for CollectionView, so this definitely points to a bug:

CollectionView testView = new CollectionView(this.GetTestStrings());

private IEnumerable<string> GetTestStrings() {
    yield return "One";
    yield return "Two";
    yield return "Three";
    yield return "1-One";
    yield return "1-Two";
    yield return "1-Three";
}
like image 3
CodeNaked Avatar answered Nov 05 '22 11:11

CodeNaked