我有一个简单的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>
。存在显式转换(您是否缺少演员表?)
我在做什么错了?
答案 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>
的方法签名...因此,除非TResult
是Document
的类型(在T
和TResult
上都需要约束),它们不能直接转换。
有一个mapping
参数,它似乎是一个转换器/投影函数,因此您可能要使用:
return response.Results.Select(mapping);
PS:@Sweeper通过查看API可以发现:
return response.Results.Select(x => Document).Select(mapping);
答案 2 :(得分:-2)
类型TResult
和类型r.Document
之间的关系是什么。您是否缺少对TResult
的限制?