我想创建一个通用的方法,我想用于混合基于属性的对象的列表。或者,您可以提供一个列表对象列表,将一些组合并在一起。这工作正常,作为一个非泛型方法,当我手动编写代码的性能等c#如何使用通用IEnumerable上的包含<T>
方法头:
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()
代替,但我已经撞了南墙:(
任何帮助将是巨大的,谢谢!
而且,让我知道,如果你需要更多的信息,但我猜想,在本质上,我需要知道的是如何使用<T>
使用.Contains()
。
它们设置为相同类型?自定义IEqualityComparer
?
为什么不直接将'GetValue'的结果转换为'T'? – Evk
如果你可以将'T'约束到一个基类型或接口,它将会有很大的帮助。 –
除非您将'T'转换为特定类型,否则它是已知的 – Rahul