Lambda“无法从使用中推断”

时间:2009-02-09 14:49:12

标签: 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

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

编辑 - 这是星期一上午的工作。

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

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

这比它应该更复杂!

3 个答案:

答案 0 :(得分:7)

你想做什么?例如,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);
    }
}

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

答案 1 :(得分:3)

  

存在显式转换(您是否错过了演员?)

有两种Where方法,一种位于System.Linq.Enumerable(正在使用),另一种位于System.Linq.Queryable上(根据该返回类型,您认为它应该使用)

您需要执行以下操作之一:

  • 将返回类型更改为IEnumerable<Image> - 我建议这样做!
  • 将方法调用更改为Queryable.Where(dictionary.Values.AsQueryable(), exp)
  • 致电AsQueryable()

答案 2 :(得分:2)

IDictionary<TKey, TValue>实施IEnumerable<KeyValuePair<TKey,TValue>>,因此Func应该更像Func<KeyValuePair<TKey,TValue>>