2011-01-08 430 views
0
class first 
{ 
    private int? firstID; 
} 

class second 
{ 
    private int secondID; 
    private int secondField; 
} 

public override Expression<Func<first, bool>> FirstFilter() 
{ 
    Contex db = new Contex(); 
    List<second> list = (from p in db.second select p).ToList(); 

    return b => list.Select(p => p.secondID).Contains(b.firstID); 
} 

,我有錯誤:無法從 'System.Collections.Generic.IEnumerable <int>' 轉換爲 'System.Collections.Generic.IEnumerable <int?>'

cannot convert from 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.IEnumerable'

我已經嘗試了很多不同的方式,但我只是不知道我該如何解決它。

回答

4

使用此:

list.Select(p => p.secondID).Cast<int?>().Contains(b.firstID); 

你得到的問題,因爲list.Select(p => p.secondID)將是一個IEnumerable<int?,但由於firstID是int(非空的),重載決策不能確定有效的過載保護包含打電話。你不能隱含地從IEnumerable<int?>轉換爲IEnumerable<int>。 Cast擴展方法通過將每個元素轉換爲int來工作。

作爲另一個答覆中提到,你也可以簡單地通過在非可空INT到包含:

list.Select(p => p.secondID).Contains(b.firstID ?? 0); 

不過,你要知道,這可能不是想要的。如果第一個列表包含0,並且firstID爲空,其結果將是真實的,因爲你在0傳遞時的值是表達的null.The鑄造版返回false時firstID爲空。

+0

完美,非常感謝,我知道哪裏出了問題,但din't知道怎麼投 – kosnkov 2011-01-08 13:55:54

0

試用firstID提供一個默認值,如果它是空:

return b => list.Select(p => p.secondID).Contains(b.firstID ?? 0); 
相關問題