使用LINQ查詢泛型字典Dictionary
具體步驟說明如下。
(1)創(chuàng)建泛型字典students(類型為Dictionary,Student1>),并添加4個Student1類型的元素,元素的鍵值分別為1~4。
(2)使用LINQ查詢泛型字典students中的所有元素,并按照元素的總分的升序排序。查詢結果保存在values變量中。
(3)把查詢結果(學生姓名及總成績)輸出到Web表單中。
具體實現代碼如下:
private void DictionaryQuery(){
StringBuilder str = new StringBuilder("");
//構建數據源
Dictionary students = new Dictionary();
students.Add(1,
new Student1
{
Name = "Svetlana",
Scores = new int[] { 98, 92, 81, 60 }
});
students.Add(2,
new Student1
{
Name = "Claire",
Scores = new int[] { 75, 84, 91, 39 }
});
students.Add(3,
new Student1
{
Name = "Sven",
Scores = new int[] { 88, 94, 65, 91 }
});
students.Add(4,
new Student1
{
Name = "Cesar",
Scores = new int[] { 97, 89, 85, 82 }
});
///查詢泛型字典
var values = from u in students
let temp = u.Value.Scores.Sum()
orderby temp
select new { name = u.Value.Name, totalscore = temp };
///顯示查詢結果
foreach (var v in values)
{
str.AppendFormat("學生姓名:{0},總分是:{1}
",v.name,v.totalscore);}
//把查詢結果顯示于Web表單中
Label1.Text = str.ToString();
}
注意到,本例中在查詢中利用了聚合查詢之一,即Sum操作,求出當前學生的總分。
本例的輸出結果如圖所示。
【編輯推薦】