Skip to main content
 首页 » 编程设计

c#之通用和非通用集合之间的 linq `from` 子句

2024年01月31日23birdshome

我有这些 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) .

然后编译器告诉我:

Error 1 An expression of type 'System.Collections.IEnumerable' is not allowed in a subsequent from clause in a query expression with source type 'System.Collections.Generic.IEnumerable'. Type inference failed in the call to 'SelectMany'.

我完全不知道发生了什么。 这里有什么问题吗?

[编辑]

我想问题是因为 collection和 propertiesToFlat是通用集合,我正在尝试设置 from带有非泛型的子句 IEnumerable .

我该如何解决?

请您参考如下方法:

基本上,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>()