泛型集合和非泛型集合之间的linq`from`子句
本文关键字:集合 泛型 子句 linq from 之间 | 更新日期: 2023-09-27 18:23:48
我在一个句子中有这些linq from
子句:
IEnumerable<T> collection = //...;
IEnumerable<PropertyInfo> propertiesToFlat = typeof(T).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(FlattenAttribute)));
var accessorFieldsbyLevel = from element in collection
from property in propertiesToFlat
from internalField in (IEnumerable<object>)(typeof(T).GetProperty(property.Name).GetValue(element))
//...
这句话很有意思。但是,我需要替换下一个from
条款:
from internalField in (IEnumerable<object>)(typeof(T).GetProperty(property.Name).GetValue(element))
由这个:
from internalField in (IEnumerable)(typeof(T).GetProperty(property.Name).GetValue(element))
所以,我只是将(IEnumerable<object>)
转换为另一个(IEnumerable)
。
然后编译器告诉我:
错误1在源类型为"System.Collections.Generic.IEnumerable"的查询表达式的后续from子句中,不允许使用类型为"System.Collections.IEnumerable"的表达式。对"SelectMany"的调用中类型推理失败。
我完全不知道发生了什么。这里怎么了?
[EDIT]
我想问题是因为collection
和propertiesToFlat
是泛型集合,所以我试图用非泛型IEnumerable
设置from
子句。
我该怎么解决?
基本上,LINQ包含非常的少数操作,这些操作可用于非泛型集合。例如,没有Enumerable.Where(IEnumerable, ...)
,只有Enumerable.Where<T>(IEnumerable<T>, ...)
。
解决此问题的最简单方法是在查询中使用显式类型的范围变量,这将插入对Enumerable.Cast<T>(IEnumerable)
:的调用
from object internalField in (IEnumerable)(typeof(T).GetProperty(property.Name).GetValue(element))
这相当于:
from internalField in
((IEnumerable)(typeof(T).GetProperty(property.Name).GetValue(element))
.Cast<object>()