2015-06-29 71 views
3

嘗試創建Lambda表達式以從包含七個Guid值中的任何一個的數據庫中選擇記錄。多個Guid的Lambda表達式

當我嘗試以下方法:

searchedOpps = searchedOpps.Where(s => s.STAGEID == stageAGuid && stageAPlusGuid && //etc); 

我得到一個Operator '&&' cannot be applied to operands of type 'bool' and 'System.Guid',同爲||(不知道這還是我應該使用這兩種運營商的)

如果我嘗試:

searchedOpps = searchedOpps.Where(s => s.STAGEID == stageAGuid); 
searchedOpps = searchedOpps.Where(s => s.STAGEID == stageAPlusGuid); 

沒有返回

的是否大人可以幫助我嗎?

+0

您必須重複變量名稱。 'searchableOpps = searchingOpps.Where(s => 1stageAGuid || s.STAGEID == stageAPlusGuid || // etc)' – xanatos

+0

來自數據庫? – rpax

回答

2

您需要「或」您的條件並每次指定比較。

searchedOpps = searchedOpps.Where(s => s.STAGEID == stageAGuid || 
             s.STAGEID == stageAPlusGuid || //etc); 

請注意,連續調用Where會將條件「與」在一起。

searchedOpps = searchedOpps.Where(s => s.STAGEID == stageAGuid); 
searchedOpps = searchedOpps.Where(s => s.STAGEID == stageAPlusGuid); 

相同

searchedOpps = searchedOpps.Where(s => s.STAGEID == stageAGuid && 
             s.STAGEID == stageAPlusGuid); 
6

在你的第二個例子,你正在尋找的對象與STAGEID == stageAGuidSTAGEID == stageAPlusGuid。你沒有得到任何結果也就不足爲奇了。

在你的第一個例子中,你只需要重複的關鍵要比較:

searchedOpps = searchedOpps 
       .Where(s => s.STAGEID == stageAGuid 
       || s.STAGEID == stageAPlusGuid [...]); 

你寫它的方式,編譯器試圖獲取bool通過「OR荷蘭國際集團」一bool(從第一次比較)和GUID&&之後的值)。

6

如果你有OR運營商,這在C#是||一些鍵,樣品你可以試試這個:

searchedOpps = searchedOpps.Where(s => s.STAGEID == stageAGuid 
            || s.STAGEID == stageAPlusGuid)); 

但是,如果你有鑰匙的列表,你可以嘗試使用Contains方法,樣品:

List<Guid> guids = /* get your keys from somewhere */; 
searchedOpps = searchedOpps.Where(s => guids .Contains(s.STAGEID)); 

如果您正在使用LINQ到數據庫工作(LINQ到SQL,實體框架,NHibernate的,等等),它會生成IN運算符的查詢與您的所有鑰匙。

2

可以使用PredicateBuilder類:

var searchPredicate = PredicateBuilder.False<Songs>(); 

searchPredicate = searchPredicate.Or(g=> g == stageAGuid); 
searchPredicate = searchPredicate.Or(g=> g == stageAPlusGuid); 

searchedOpps = searchedOpps.Where(searchPredicate); 
1

你不說你正在使用的系統進行數據訪問,所以我會承擔它的EF和至少.NET 4

如果您正確編寫查詢,LINQ-to-Entities會將其轉換爲SQL「in」子句。看看這個MSDN項:

http://blogs.msdn.com/b/alexj/archive/2009/03/26/tip-8-writing-where-in-style-queries-using-linq-to-entities.aspx

如果您正在尋找7點不同的GUID,做這樣的事情:

Guid[] myGuidList = 
    { stageAGuid, stageAPlusGuid, anotherGuid, guid4, guid5, guid6, guid7, }; 

var results = searchedOpps.Where(s => myGuidList.Contains(s.STAGEID)); 

產生的SQL如下所示:

select * from searchedOpps where STAGEID in (<guid>, <guid>, <guid>...)