我想創建一個通用的方法,我想用於混合基於屬性的對象的列表。或者,您可以提供一個列表對象列表,將一些組合並在一起。這工作正常,作爲一個非泛型方法,當我手動編寫代碼的性能等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