LAMBDA

2009-02-09 75 views
7

我有以下字典宣稱「不能從使用推斷」: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 

作爲一個供參考,對於實現一個接口,聲明的方法那就是:

IQueryable<T> Find(Func<T, bool> exp); 

這已經變得比它應該更復雜了!

+0

正如我已經說過 - 返回類型更改爲IEnumerable的 2009-02-09 15:18:58

回答

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

(我不知道它是更難呼叫者這個做自己,雖然)

+0

的.values位正是我需要的真的,所以你得到的答案。我已編輯我的問題,以澄清我要去哪裏 – qui 2009-02-09 15:01:24

+0

請注意,在哪裏你通常會返回IEnumerable 等 - 很高興你得到它排序,雖然; - – 2009-02-09 15:03:04

2

IDictionary<TKey, TValue> implements IEnumerable<KeyValuePair<TKey,TValue>>,所以你的Func應該看起來更像Func<KeyValuePair<TKey,TValue>>

3

An explicit conversion exists (are you missing a cast?)

有兩種Where方法,一個是關於System.Linq.Enumerable(它使用),以及一個在System.Linq.Queryable(你認爲它應該使用,根據返回類型)。

你需要做以下之一:

  • 變化返回類型IEnumerable<Image> - 我推薦這個!
  • 變化的方法調用Queryable.Where(dictionary.Values.AsQueryable(), exp)
  • 呼叫AsQueryable()