我在我的代码中收到一个IEnumerable<T>。它可以是未分组的平面IEnumerable<T>,也可以是分组的a。
因此,我使用我写的小的、漂亮的小扩展检查这是否:
public static bool IsABunchOfGroups<T>(this IEnumerable<T> source)
{
return typeof(T).IsAssignableFrom(typeof(IGrouping<,>));
}但是,一旦检查了,如果它是一个IEnumerable<IGrouping<,>>,我想把它转换成这样,这样IEnumerable<T>中的每个T都会转换成IGrouping<,>,其中我不知道IGrouping<,>的泛型参数是什么。
我正在努力做到这一点。
所以,这是我想要的:
void WriteSequenceToStream(IEnumerable<T> sequence)
{
if (sequence.IsABunchOfGroups())
{
foreach(var t in sequence)
{
// t as IGrouping<,>
}
}
}再说一次,由于不确定泛型类型参数是什么,我甚至在这个上下文中使用dynamic关键字都是没有意义的:
void WriteSequenceToStream(IEnumerable<T> sequence)
{
if (sequence.IsABunchOfGroups())
{
foreach(var t in sequence)
{
// t as IGrouping<,>
dynamic element = t;
someTextWriter.WriteLine(element.Key);
foreach(dynamic item in element)
{
// Oh yeah, may be I could! Anyway, still
// is there a way I could do it without the dynamic keyword?
// I think I am asking a question I've asked in the past
// many times already, in one form or another
}
}
}
}发布于 2014-06-01 12:14:43
为什么不干脆:
Collection.Select(item => (TheTypeYouWant)item);https://stackoverflow.com/questions/23976667
复制相似问题