C# 中的 Dictionary.Item[] 属性
C# 中的 Dictionary.Item[] 属性用于获取或设置 Dictionary 中与指定键关联的值。
语法
以下是语法 −
public TValue this[TKey key] { get; set; }示例
我们现在看一个示例来实现 Dictionary.Item[] 属性 −
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Dictionary<string, string> dict =
new Dictionary<string, string>();
dict.Add("One", "Chris");
dict.Add("Two", "Steve");
dict.Add("Three", "Messi");
dict.Add("Four", "Ryan");
dict.Add("Five", "Nathan");
Console.WriteLine("Count of elements = "+dict.Count);
Console.WriteLine("
Key/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
Console.WriteLine("Value for key three = "+dict["Three"]);
dict["Three"] = "Ronaldo";
Console.Write("Updated value associated with key Three...");
Console.WriteLine(dict["Three"]);
if (dict.ContainsValue("Angelina"))
Console.WriteLine("
Value found!");
else
Console.WriteLine("
Value isn't in the dictionary!");
dict.Clear();
Console.WriteLine("Cleared Key/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
Console.WriteLine("Count of elements now = "+dict.Count);
}
}输出
这将产生以下输出 −
Count of elements = 5 Key/value pairs... Key = One, Value = Chris Key = Two, Value = Steve Key = Three, Value = Messi Key = Four, Value = Ryan Key = Five, Value = Nathan Value for key three = Messi Updated value associated with key Three...Ronaldo Value isn't in the dictionary! Cleared Key/value pairs... Count of elements now = 0
示例
我们现在看另一个示例来实现 Dictionary.Item[] 方法 −
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Dictionary<string, string> dict =
new Dictionary<string, string>();
dict.Add("One", "Chris");
dict.Add("Two", "Steve");
dict.Add("Three", "Messi");
dict.Add("Four", "Ryan");
dict.Add("Five", "Nathan");
Console.WriteLine("Count of elements = "+dict.Count);
Console.WriteLine("
Key/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
Console.WriteLine("Value for key three = "+dict["Three"]);
dict["Three"] = "Katie";
Console.Write("Updated value associated with key Three...");
Console.WriteLine(dict["Three"]);
}
}输出
这将产生以下输出 −
Count of elements = 5 Key/value pairs... Key = One, Value = Chris Key = Two, Value = Steve Key = Three, Value = Messi Key = Four, Value = Ryan Key = Five, Value = Nathan Value for key three = Messi Updated value associated with key Three...Katie
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP