Linq中的Select與Select many


Select與Select Many

之前在項目中查詢數據庫中的數據,都是通過sql語句來查詢的,但是隨着時代的發展,微軟在.Net Framework 4.5版中推出的一個主要的特性——LINQ。

LINQ是Language Integrate Query的縮寫,意為語言集成查詢。其中有兩種查詢方式,分為語句查詢和方法查詢。

語句查詢:from a in Table

              select  a ;

方法查詢:Table.select(x=>x)

今天要講的是方法查詢中的Select與Select Many。

select:將序列中的每個元素投影到新表中(官方定義)。個人理解:就是查詢什么得到什么,比如查詢表的所有元素,那么就得到表里的所有元素,不對得到的元素作出修改(Table.select(x=>x))。

select many:將序列的每個元素投影到一個 System.Collections.Generic.IEnumerable`1,並將結果序列組合為一個序列。

參考:https://www.cnblogs.com/zhangyuanbo12358/p/4107882.html 例子1:select

1 string[] text = { "Today is 2018-06-06", "weather is sunny", "I am happy" };
2 
3             var tokens = text.Select(s => s.Split(' '));
4             foreach (string[] line in tokens)
5 
6                 foreach (string token in line)
7 
8                     Console.Write("{0}.", token);
9             Console.ReadKey();

結果:

select many:

1 string[] text1 = { "Today is 2018-06-06", "weather is sunny", "I am happy" };
2             var tokens1 = text1.SelectMany(s => s.Split(' '));
3             foreach (string token in tokens1)
4             Console.Write("{0}.", token);            
5             Console.ReadKey();

結果和上圖一樣。結論:在select中,首先對字符串“Today is 2018-06-06”按照“ ”進行切割,變成字符串數組{“Today”,“is”," 2018-06-06"},但是select many則是在此基礎上,對得到的序列進行重組,即將數組中的元素進行合並,變成字符串“Todayis2018-06-06”,

這就是兩者的區別。

當然最重要的還是什么時候用select ,什么時候用select many呢?

     如果你是僅僅查詢表中的某個列(屬性)的,並對其使用聚合函數(sum,count,avg),那么select適合你  StudentTable.select(x=>x.age>=20).count()——查詢學生表中年齡大於20的人數

    如果你查詢表中的某個集合,但是你又想對集合里的對象進行聚合,那么select many適合你 SchoolTable.SelectMany(x => x.StudentCollection).Where(y => y.age >=20).count()——查詢學校表里中的學生表中年齡大於20的人數,

X:school類里的StudentCollection屬性,該屬性類型是集合,集合里存放的是student對象。Y:student對象

以上就是本人對select 與select many的見解,如果有什么不對的地方,歡迎指正,謝謝

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM