使用LINQ查询泛型字典Dictionary

具体步骤说明如下。

(1)创建泛型字典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操作,求出当前学生的总分。

本例的输出结果如图所示。

【编辑推荐】

  1. 浅谈LINQ to SQL集成数据库语言优劣
  2. 浅谈LINQ如何插入删除和更新数据库记录备注
  3. 基于LINQ to SQL的WEB开发三层架构
THE END