c# - λ "cannot be inferred from the usage"

标签 c# linq 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

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

编辑 - 这是周一早上上类。

我是想放“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/

相关文章:

c# - 在小键盘 View 打开的情况下启动 TabTip

asp.net-mvc - ASP.NET 使用 LINQ 处理 DB 表单

c# - 无法将 LINQ Query var 转换为 DataTable

c# - 复杂的 LINQ 查询来构建两个列表、转换每个列表中的每个值并组合列表?

c++ - 如何保存 lambda 以供以后回调?

c# - 如何进行无缝代码推送(为什么 Page._fPageLayoutChanged 很重要)?

c# - C# 中的聚合与继承,或替代方案

c# - Windows 应用商店应用程序开发 - InvalidateRequerySuggested

lambda - 如何使用 Google Blogger Lambda 运算符

python - 如何通过python使用lambda函数从列表中删除负值