2016-04-28 92 views
0

繼續從my original question開始,它已成功獲得答案。將函數傳遞給Contains Linq方法

爲什麼下面的代碼工作,並且當我包含Where()方法時更通用的例子失敗?

// *** WORKS *** 
private IEnumerable<int> _MySelectedData; 
public void method() 
{ 
    IEnumerable<int> distinctData = GetData(m => m.ModelID); 
} 
public IEnumerable<int> GetData(Func<Model, int> selectParam) 
{ 
    return _MyData 
     .Where(m => _MySelectedData.Contains(m.ManufacturerID)) 
     .Select(selectParam).Distinct(); 
} 



// *** FAILS *** 
private IEnumerable<int> _MySelectedManufacturers; 
public void method() 
{ 
    IEnumerable<int> distinctData = GetData(_MySelectedManufacturers, m => m.ManufacturerID, m => m.ModelID); 
} 
public IEnumerable<int> GetData(IEnumerable<int> _MySelectedData, Func<Model, int> whereParam, Func<Model, int> selectParam) 
{ 
    return _MyData 
     .Where(m => _MySelectedData.Contains(whereParam)) 
     .Select(selectParam).Distinct(); 
} 

我得到以下錯誤:

'IEnumerable' does not contain a definition for 'Contains' and the best extension method overload 'Queryable.Contains...

出現的錯誤在這行:

.Where(m => _MySelectedData.Contains(whereParam)) 

希望有人能凸顯錯誤在我的方式!

回答

2

Contains需要作爲參數,但你傳遞一個功能。我懷疑你只是想評估功能對「當前」項目:

.Where(m => _MySelectedData.Contains(whereParam(m))) 
+0

非常感謝,我是如此接近的解決方案,但你的幫助幫助解決它。 – X22