LINQ查詢表達式中的復合from子句
<!--[if !supportLists]-->1. <!--[endif]-->功能
from子句負責指定LINQ查詢操作中的數據源和范圍變量。
<!--[if !supportLists]-->2. <!--[endif]-->語法要求
①每一個LINQ查詢表達式都必須包含from子句,且必須以from子句開頭。
②如果LINQ查詢表達式還包含子查詢,那么子查詢表達式也必須以from子句開頭。
③數據源不但包括LINQ查詢本身的數據源,而且還包括子查詢的數據源。范圍變量一般用來表示源序列中的每一個元素。
④from子句指定的數據源的類型必須為IEnumerable、IEnumerable
⑤在from子句中,如果數據源實現了IEnumerable
<!--[if !supportLists]-->3. <!--[endif]-->
復合from子句查詢舉例
在有些情況下,數據源的每一個元素本身可能還包含另一個子數據源(如序列、列表等)。此時,如果要查詢子數據源中的元素,則需要使用復合類型的from子句。
下面的實例演示了復合from子句查詢的方法,具體步驟說明如下。
(1)創建數據類型為List
(2)使用復合from子句查詢每個學生的各個大于90分的科目成績信息。第1個from子句負責查詢students數據源,第2個from子句則用于查詢student.Scores數據源。
(3)使用foreach語句輸出查詢的結果,并把此結果最終顯示于ASP.NET服務器標簽控件中。
- public class Student
- {
- public string LastName { get; set; }
- public List Scores { get; set; }
- }
- ……(省略)
- StringBuilder str = new StringBuilder("");
- //建立數據源
- List students = new List
- {
- new Student {LastName="Omelchenko", Scores= new List {97, 97, 81, 60}},
- new Student {LastName="O'Donnell", Scores= new List {75, 80, 91, 39}},
- new Student {LastName="Mortensen", Scores= new List {88, 94, 65, 85}},
- new Student {LastName="Garcia", Scores= new List {97, 89, 99, 82}},
- new Student {LastName="Beebe", Scores= new List {35, 94, 91, 70}}
- };
- //使用復合from子句循環搜索出每個學生的各個大于90分的成績
- var scoreQuery =
- from student in students
- from score in student.Scores
- where score > 90
- select new { Last = student.LastName, score };
- //顯示查詢結果
- foreach (var v in scoreQuery)
- {
- str.Append(v.Last +" "+v.score+ " ");
- }
- Label1.Text = "";
- Label1.Text = str.ToString();
下圖給出了上例的LINQ查詢運行結果快照。
【編輯推薦】