c# – Lambda“无法从使用中推断”

我声明了以下字典:
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

我试过谷歌搜索,我似乎找不到任何关于我做错了什么的确定

编辑 – 这是星期一早上上班.

我的意思是把“在哪里”,而不是单身

编辑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

作为一个FYI,有实现接口的方法,其声明是:

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);
}

当然,您可以通过以下方式全局作为扩展方法

(编辑包括问题编辑的位置)

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,bool> predicate)
    {
        return dictionary.Values.Where(predicate);
    }
}

(我不确定调用者自己做这件事要困难得多)

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...