【发布时间】:2014-08-19 23:20:18
【问题描述】:
我正在尝试构建一个通用过滤器控件,它在数据网格中显示唯一值,并让用户过滤网格中特定列的唯一值。
我喜欢为this question 提出的答案,但是所有这些都要求您事先了解该属性。我想编写代码OCP compliant,并且只有一种方法可以获取属性名称字符串并在其上应用不同的函数(可能使用反射)。考虑到我的列(因此要过滤的列名,如姓名、年龄等是动态的),什么是这个问题的最佳解决方案。
具体来说,我试图避免这种 switch case 语句:
switch (listColumn.DisplayMemberPath)
{
case "Name" :
listColumn.Items = GridItems.GroupBy(item => item.Name).Select(item => item.First());
break;
case "Age" :
listColumn.Items = GridItems.GroupBy(item=> item.Age).Select(item => item.First());
break;
// and so on...
}
并且有一个像这样的通用方法:
public IEnumerable GetDistinctValues(IEnumerable gridItems, string propertyName)
{
// logic to return the distinct values for the given property name...
}
仅供参考 - 我在 ViewModel 中的集合是 ICollectionView 类型(猜测在 CollectionView 中已经定义了类似的东西来执行我正在寻找的那种过滤)。
【问题讨论】:
-
您基本上是在寻找
DistinctBy方法。查看接受的答案here。 -
抱歉,我不知道接受的答案是否适合我。请看我的问题:我需要能够通过使用属性名称来应用 distinct,所以我不能将 object.property 传递给这个方法。
标签: c# linq icollectionview open-closed-principle