字典对象的集合初始化器和查询表达式






2.57/5 (4投票s)
本文解释了在 C# 3.0 中使用集合初始化器和查询表达式的语法,用于字典对象。
引言
本文解释了在 C# 3.0 中使用集合初始化器和查询表达式的语法,用于 Dictionary
对象。
背景
我正在学习 C# 3.0 的新特性。虽然集合初始化器和查询表达式在大多数情况下使用起来都很简单直接,但它们与 Dictionary
对象一起使用的情况却鲜有文档记录。因此,本文提供了一个初学者级别的视角,来理解与 Dictionary
对象一起使用集合初始化器和查询表达式。
Using the Code
在下面的代码块中,定义了一个 Dictionary
对象(currencyCollection
)。Key 存储 ID,Value 存储不同的货币。
//Collection Initializers
Dictionary<int, string> currencyCollection = new Dictionary<int, string> {
{1,"Indian Rupee"},
{2, "United States Dollar"},
{3, "Euro"},
{4, "British Pound"},
{5, "Australian Dollar"},
{6, "Japanese Yen" },
{7,"Indian Rupee"}
};
下一步,我使用查询表达式查询货币“Indian Rupee
”(印度卢比)。此表达式将找到“Indian Rupee
”的条目。
//Query Expressions
var query = from c in currencyCollection
where (c.Value.Equals("Indian Rupee"))
select c;
现在,变量 query 包含过滤后的仅“Indian Rupee
”对象。我使用一个简单的 foreach
循环来显示结果。
//Iterate through the dictionary and print
foreach (var ky in query)
Console.WriteLine("{0}, {1}", ky.Key.ToString(), ky.Value);
关注点
我学到的两点是:
- 如何为
Dictionary
对象使用集合初始化器。 - 如何为
Dictionary
对象使用查询表达式。
历史
- 创建日期:2009-2-11