我声明了以下字典:
private readonly Dictionary<int, Image> dictionary;
我有一个导致编译器错误的方法:
public IQueryable<Image> Find(Func<Image, bool> exp)
{
return dictionary.Single(exp);
}
我得到的错误是:
Error 1 The type arguments for method 'System.Linq.Enumerable.Single<TSource>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,bool>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. C:\work\MSD-AIDS-Images\MSD-AIDS-Images-Test\TestImageRepository.cs 34 30 MSD-AIDS-Images-Test
我试过谷歌搜索,我似乎找不到任何关于我做错了什么的明确信息
编辑 - 这是周一早上上类。
我是想放“where”,而不是单个
编辑2!
好的,现在的代码是这样的:
public IQueryable<Image> Find(Func<Image, bool> exp)
{
return dictionary.Values.Where(exp);
}
现在我得到以下错误:
Error 1 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<MSD_AIDS_Images_Data.Image>' to 'System.Linq.IQueryable<MSD_AIDS_Images_Data.Image>'. An explicit conversion exists (are you missing a cast?) C:\work\MSD-AIDS-Images\MSD-AIDS-Images-Test\TestImageRepository.cs 34 20 MSD-AIDS-Images-Test
仅供引用,这里有实现接口(interface)的方法,其声明是:
IQueryable<T> Find(Func<T, bool> exp);
这比它应该的更复杂!
最佳答案
你想做什么?例如,Single
将返回 T
的实例,不是 IQueryable<T>
(对于对象,无论如何你应该使用 IEnumerable<T>
)...
感觉就像你想要的:
public Image Find(Func<Image, bool> predicate)
{
return dictionary.Values.Single(predicate);
}
当然,您可以通过以下方式作为扩展方法在全局范围内执行此操作:
(编辑包括来自问题编辑的Where
)
static class DictionaryExtensions
{
public static TValue FindSingle<TKey, TValue>(
this IDictionary<TKey, TValue> dictionary,
Func<TValue, bool> predicate)
{
return dictionary.Values.Single(predicate);
}
public static IEnumerable<TValue> Find<TKey, TValue>(
this IDictionary<TKey, TValue> dictionary,
Func<TValue, bool> predicate)
{
return dictionary.Values.Where(predicate);
}
}
(不过,我不确定调用者自己做这件事是否更难)
关于c# - λ "cannot be inferred from the usage",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/528430/