Linq 中 Any与All
生活随笔
收集整理的這篇文章主要介紹了
Linq 中 Any与All
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
昨天突然看到之前寫的一個積累文檔,其中文檔中有一個Linq Any和All的注意事項:
看看他生成的SQL,我們就知道原因了
?2?DECLARE?@p0?NVarChar(1000)?=?''
?3?--?EndRegion
?4?SELECT?
?5?????(CASE?
?6?????????WHEN?NOT?(EXISTS(
?7?????????????SELECT?NULL?AS?[EMPTY]
?8?????????????FROM?[Test]?AS?[t1]
?9?????????????WHERE?(
10?????????????????(CASE?
11?????????????????????WHEN?[t1].[OpenId]?=?@p0?THEN?1
12?????????????????????ELSE?0
13??????????????????END))?=?0
14?????????????))?THEN?1
15?????????WHEN?NOT?NOT?(EXISTS(
16?????????????SELECT?NULL?AS?[EMPTY]
17?????????????FROM?[Test]?AS?[t1]
18?????????????WHERE?(
19?????????????????(CASE?
20?????????????????????WHEN?[t1].[OpenId]?=?@p0?THEN?1
21?????????????????????ELSE?0
22??????????????????END))?=?0
23?????????????))?THEN?0
24?????????ELSE?NULL
25??????END)?AS?[value]
?3?--?EndRegion
?4?SELECT?
?5?????(CASE?
?6?????????WHEN?EXISTS(
?7?????????????SELECT?NULL?AS?[EMPTY]
?8?????????????FROM?[Test]?AS?[t0]
?9?????????????WHERE?[t0].[OpenId]?=?@p0
10?????????????)?THEN?1
11?????????ELSE?0
12??????END)?AS?[value]
注意Any 和 All
??????????? var list = new List<int>();
??????????? var aa = list.All(n => n > 1);
??????????? var bb = list.Any(n => n > 1);
??????????? // aa: true?????? bb: false
?
其中List是一個元素個數為0的整型List。可能大多數人跟我一樣,第一次見到都會認為aa為false。然后這個是我在程序中寫Linq的時候,造成了很大困惑,明明條件是正確的(當時一直認為aa為false),卻結果不對。?最后一句一句,一個條件一個條件的拆分了執行,才找到這個原因。看看他生成的SQL,我們就知道原因了
All: ? ? ?IQueryable<Test>.All(t=>t.OpenId=="")
?1?--?Region?Parameters?2?DECLARE?@p0?NVarChar(1000)?=?''
?3?--?EndRegion
?4?SELECT?
?5?????(CASE?
?6?????????WHEN?NOT?(EXISTS(
?7?????????????SELECT?NULL?AS?[EMPTY]
?8?????????????FROM?[Test]?AS?[t1]
?9?????????????WHERE?(
10?????????????????(CASE?
11?????????????????????WHEN?[t1].[OpenId]?=?@p0?THEN?1
12?????????????????????ELSE?0
13??????????????????END))?=?0
14?????????????))?THEN?1
15?????????WHEN?NOT?NOT?(EXISTS(
16?????????????SELECT?NULL?AS?[EMPTY]
17?????????????FROM?[Test]?AS?[t1]
18?????????????WHERE?(
19?????????????????(CASE?
20?????????????????????WHEN?[t1].[OpenId]?=?@p0?THEN?1
21?????????????????????ELSE?0
22??????????????????END))?=?0
23?????????????))?THEN?0
24?????????ELSE?NULL
25??????END)?AS?[value]
?可以看得出來, All 是用的 Not (Exists) , 當Query為空的時候,Exists是為false的,而前面一個Not (false),當然也成為了True;
?Any: ? ? ? ? ?IQueryable<Test>.Any(t=>t.OpenId=="")
??1?--?Region?Parameters
?2?DECLARE?@p0?NVarChar(1000)?=?''?3?--?EndRegion
?4?SELECT?
?5?????(CASE?
?6?????????WHEN?EXISTS(
?7?????????????SELECT?NULL?AS?[EMPTY]
?8?????????????FROM?[Test]?AS?[t0]
?9?????????????WHERE?[t0].[OpenId]?=?@p0
10?????????????)?THEN?1
11?????????ELSE?0
12??????END)?AS?[value]
?
可以看出 ? Any生成的是Exists。??當Query為空的時候,Exists是為false的。
?
轉載于:https://www.cnblogs.com/AaronAndJoe/p/4642231.html
總結
以上是生活随笔為你收集整理的Linq 中 Any与All的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 光大咿啦看书联名信用卡怎么样?首款儿童阅
- 下一篇: 性能超越RTX 3050!联想小新Pro