C#中Collection和Dictionary的foreach遍历方式 .

最近在项目中要使用Dictionary对象。以前很少用到。现在就学习一下

Dictionary是表示键和值的集合,Dictionary<(TKey, TValue>)>泛型类提供了从一组键到一组值的映射。字典中的每个添加项都由一个值及其相关联的键组成。通过键来检索值的速度是非常快的,接近于 O(1),这是因为 Dictionary<(TKey, TValue>) 类是作为一个哈希表来实现的。但是里面的值必须是唯一的才行。其中Tkey是字典中的键的类型,TValue是字典中的值的类型。

对于已经存在的Dictionary对象,我们可以通过这样的方式来获取里面的值 dic["key"] = "value";

如果想对其遍历的话,可以使用这样的方式

foreach (KeyValuePair<string, string> kvp in openWith) //遍历输出里面的值

Response.Write(kvp .Key +" "+kvp .Value +"<br>");

对于枚举而言,字典中的每一项都被视为一个表示值及其键的 KeyValuePair<(TKey, TValue)> 结构进行处理。

由于在dictionary的值集合里面,我们可以存储对象,那么我们怎么利用现在的linq来查询呢。其实,通过下面的例子大家就会了解。

//构建Dictionary对象的数据源

Dictionary<int, Student1> students = new Dictionary<int, Student1>();

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)

{

Console.WriteLine("学生姓名:{0},总分是:{1}", v.name, v.totalscore);

}

Console.ReadLine();

本例中在查询中利用了聚合查询之一,即Sum操作,求出当前学生的总分。

从上面的例子就可以看出。只要是集成自IEnumerable接口的对象,都可以使用linq或者使用lamda表达式来进行查询,很是方便

最近在项目中要使用Dictionary对象。以前很少用到。现在就学习一下

Dictionary是表示键和值的集合,Dictionary<(TKey, TValue>)>泛型类提供了从一组键到一组值的映射。字典中的每个添加项都由一个值及其相关联的键组成。通过键来检索值的速度是非常快的,接近于 O(1),这是因为 Dictionary<(TKey, TValue>) 类是作为一个哈希表来实现的。但是里面的值必须是唯一的才行。其中Tkey是字典中的键的类型,TValue是字典中的值的类型。

对于已经存在的Dictionary对象,我们可以通过这样的方式来获取里面的值 dic["key"] = "value";

如果想对其遍历的话,可以使用这样的方式

foreach (KeyValuePair<string, string> kvp in openWith) //遍历输出里面的值

Response.Write(kvp .Key +" "+kvp .Value +"<br>");

对于枚举而言,字典中的每一项都被视为一个表示值及其键的 KeyValuePair<(TKey, TValue)> 结构进行处理。

由于在dictionary的值集合里面,我们可以存储对象,那么我们怎么利用现在的linq来查询呢。其实,通过下面的例子大家就会了解。

//构建Dictionary对象的数据源

Dictionary<int, Student1> students = new Dictionary<int, Student1>();

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)

{

Console.WriteLine("学生姓名:{0},总分是:{1}", v.name, v.totalscore);

}

Console.ReadLine();

本例中在查询中利用了聚合查询之一,即Sum操作,求出当前学生的总分。

从上面的例子就可以看出。只要是集成自IEnumerable接口的对象,都可以使用linq或者使用lamda表达式来进行查询,很是方便