【发布时间】:2017-11-21 13:02:30
【问题描述】:
我正在尝试创建一个通用方法,我想使用它来混合基于属性的对象列表。或者,您可以提供列表对象列表以将某些组合并在一起。这可以作为非泛型方法以及当我手动对属性进行编码等时正常工作。
方法头:
public static IEnumerable<T> MixObjectsByProperty<T>(
IEnumerable<T> objects,
string propertyName,
IEnumerable<IEnumerable<T>> groupsToMergeByProperty = null)
方法主体的片段:
groups =
(from item in objects
let propertyInfo = item.GetType().GetProperty(propertyName)
where propertyInfo != null
group item by groupsToMergeByProperty
.FirstOrDefault(ids => ids.Contains(propertyInfo.GetValue(item, null)))
//.FirstOrDefault(ids => ids.Any(propertyInfo.GetValue(item, null)))
?.First()
?? propertyInfo.GetValue(item, null)
into itemGroup
select itemGroup.ToArray())
.ToList();
如您所见,我在使用 IEnumerable<T> 上的 contains 方法时遇到问题,因为 propertyInfo.GetValue(item, null) 正在返回一个对象。我尝试了各种铸造尝试并改用.Any(),但我碰上了砖墙:(
任何帮助都会很棒,谢谢!
另外,如果您需要更多信息,请告诉我,但我想,本质上,我只需要知道如何使用 .Contains() 和 <T>。
将它们设置为相同的类型?自定义IEqualityComparer?
【问题讨论】:
-
为什么不直接将
GetValue的结果转换为T? -
如果您可以将
T限制为基本类型或接口,这将大有帮助。 -
除非您将
T转换为其他已知类型,否则您不能这样做 -
为什么要传递属性名?为什么不像所有 LINQ 方法一样传递 表达式,例如使用
Func<T,T> propGetter并传递it =>it.PropName作为参数值。还是将整个条件作为表达式传递?
标签: c# linq generics ienumerable contains