使用LINQ查询泛型字典Dictionary

开发 后端
本文将为大家讲解一个使用LINQ查询泛型字典Dictionary<TKey,TValue>的例子。希望对大家学习LINQ有所帮助。

具体步骤说明如下。

(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开发三层架构
责任编辑:彭凡 来源: 51CTO
相关推荐

2009-04-24 09:33:12

LINQ查询非泛型

2009-09-08 16:36:10

LINQ查询基于泛型类

2009-09-14 18:57:19

LINQ查询

2009-08-24 18:15:24

C# Dictiona

2009-09-14 14:01:21

LINQ泛型数据集

2010-05-17 09:34:46

LINQAjax

2021-09-29 18:17:30

Go泛型语言

2009-09-08 09:24:50

LINQ查询

2009-01-04 16:58:48

LINQ to XMLLINQXML

2024-01-09 09:27:57

Rust编程泛型

2023-01-05 17:13:28

TypeScript泛型组件

2022-04-15 09:55:59

Go 泛型Go 程序函数

2009-09-01 16:14:11

C#泛型

2009-08-24 15:28:19

C# 泛型方法

2009-08-19 04:16:00

泛型代码重用

2009-09-14 10:13:02

LINQ查询操作

2009-09-09 16:53:53

LINQ查询语法

2009-09-08 17:27:18

LINQ to Dat

2009-09-14 10:09:26

LINQ查询结果

2009-09-10 16:28:17

LINQ查询
点赞
收藏

51CTO技术栈公众号