2013-07-12 209 views
2

如果有人可以在以下建議我會很感激: 我需要根據不同的條件(在我的情況適配器)來選擇不同的價值觀,我想是這樣的:條件選擇在Lambda表達式LINQ

return this.WrappedEntity.human_screen.SelectMany(e => e).Select(e => 
       { 
        AHuman human = _unitOfWork.HumansRepo.GetById(e.human_uid.ToString()); 
        if (e.vid_screen == "1" && human.Gender== Gender.Female) 
        { 
         return new SqlFemaleScreening(e); 
        } 
        else if (e.vid_screen == "1" && human.Gender== Gender.Male) 
        { 
         return new SqlMaleScreening(e); 
        } 
        else 
        { 
         return new SqlChildScreening(e); 
        } 
       }); 

但我得到以下錯誤:

ERROR: Type arguments for method " System.Linq.Enumerable.SelectMany <TSource,TResult> (System.Collections.Generic.IEnumerable <TSource>, System.Func <TSource, int, System.Collections.Generic.IEnumerable <TResult>>) "should be defined for use. Try to clearly define the type arguments.

非常感謝您提前!

+0

我認爲當你說「它不正確」時,你的意思是說有某種編譯器錯誤?它說什麼? – Chris

+0

它如何「不正確」?什麼是錯誤? – Lee

+0

它有什麼問題?它是否會拋出異常,或者您擔心代碼質量? –

回答

4

問題是,因爲你正在返回多種不同類型的對象,所以編譯器不確定你在返回的枚舉中會期待什麼對象類型。通常當你使用類似SelectSelectMany的東西時,編譯器可以解決這個問題,所以你不必擔心它。在這種情況下,你需要擔心告訴它應該是什麼。

您的代碼將被改變的樣子:

return this.WrappedEntity.human_screen.SelectMany(e => e).Select<TSource, TResult>(e => 
    { 
     //Same code as before in here 
    }); 

TSource應該是e在您選擇的方法的類型。 TResult應該是基本類型SqlFemaleScreening,SqlMaleScreeningSqlChildScreening

+0

還有別的辦法嗎?因爲我沒有基類型的SqlFemaleScreening,SqlMaleScreening,SqlChildScreening適配器。 –

+1

你期待什麼樣的返回類型?很明顯,你會從這些東西中獲得一個'IEnumerable ',你需要做的是定義T是什麼,所有的類都可以適合它。如果他們沒有共同的類型,那麼我不確定把它們全部放在同一個枚舉中的好處是什麼(並且名稱確實表明它們*應該*具有共同類型,因爲它們聽起來真的很相似...... – Chris

+0

Right ,謝謝!現在有效,但沒有SelectMany:return this.WrappedEntity.human_screen.Select (e => {} –

0

SelectMany表達式的結果應該是IEnumerable<T>,例如,

human_screen.SelectMany(e => e.Some_Collection)