您的位置:首页 > 其它

使用 IEqualityComparer来过滤PagedCollectionView里的重复数据

2010-10-22 19:53 330 查看
很多情况下我们获取的PagedCollectionView数据集内有很多重复的数据,我们可以使用 IEqualityComparer<T> 来过滤。

数据模型:

public class Product
{
public string Name { get; set; }
public int Code { get; set; }
}


建一个过滤重复内容的类:

// Custom comparer for the Product class
class ProductComparer : IEqualityComparer<Product>
{
// Products are equal if their names and product numbers are equal.
public bool Equals(Product x, Product y)
{

//Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;

//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;

//Check whether the products' properties are equal.
return x.Code == y.Code && x.Name == y.Name;
}

// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.

public int GetHashCode(Product product)
{
//Check whether the object is null
if (Object.ReferenceEquals(product, null)) return 0;

//Get hash code for the Name field if it is not null.
int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode();

//Get hash code for the Code field.
int hashProductCode = product.Code.GetHashCode();

//Calculate the hash code for the product.
return hashProductName ^ hashProductCode;
}

}


在Silverlight中调用:

if (e.Result != null)
{
try
{
PagedCollectionView pcv = new PagedCollectionView(e.Result);
List<Product> pp = new List<Product>();
foreach (Product p in pcv)
{
pp.Add(p);
}
this.listBox1.ItemsSource = pp.Distinct(new ProductComparer());
}
catch
{
MessageBox.Show("获取XX内容失败!");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐