将通用列表\转换为通用IEnumerable

时间:2019-03-11 14:24:03

标签: c# generics

我有一个简单的Azure搜索服务,我正在尝试使其通用,但是我在return部分中苦苦挣扎。

public class AzureSearchService<T> : IAzureSearchProvider<T> where T : class
{
    public IEnumerable<TResult> Search<TResult>(string searchText, string filter, 
        Func<T, TResult> mapping)
    {
        DocumentSearchResult<T> response = indexClient.Documents
            .Search<T>(searchText, searchParameters);

        return response.Results.Select(r => r.Document).ToList();
    }
}

我怀疑这可能很简单,但出现错误:

  

无法将类型隐式转换为List<T>IEnumerable<TResult>。存在显式转换(您是否缺少演员表?)

我在做什么错了?

3 个答案:

答案 0 :(得分:2)

我猜您忘记了使用mapping参数?您应该使用它!

return response.Results
            .Select(r => r.Document)
            .Select(mapping)
            .ToList(); // you don't need ToList here, unless you don't want the results to be lazy

mapping是将列表中的每个T转换为TResult的功能。

答案 1 :(得分:0)

您将返回Document对象的列表,但使用返回类型为IEnumerable<TResult>的方法签名...因此,除非TResultDocument的类型(在TTResult上都需要约束),它们不能直接转换。

有一个mapping参数,它似乎是一个转换器/投影函数,因此您可能要使用:

return response.Results.Select(mapping);

PS:@Sweeper通过查看API可以发现:

return response.Results.Select(x => Document).Select(mapping);

答案 2 :(得分:-2)

类型TResult和类型r.Document之间的关系是什么。您是否缺少对TResult的限制?