当前位置: 首页> 财经> 创投人物 > sem代运营_企业名称查重_百家港 seo服务_搜索引擎营销例子

sem代运营_企业名称查重_百家港 seo服务_搜索引擎营销例子

时间:2025/7/11 7:46:40来源:https://blog.csdn.net/2401_82978699/article/details/143182491 浏览次数:0次
sem代运营_企业名称查重_百家港 seo服务_搜索引擎营销例子

在C#中,Dictionary 是一种集合类型,用于存储键值对(key-value pairs)。它属于 System.Collections.Generic 命名空间,并提供了一种快速查找数据的方法。Dictionary 类似于哈希表或映射,允许你通过键(key)快速访问值(value)。

主要概念和特性

  1. 键值对Dictionary 中的每个元素都是一个键值对,键是唯一的,而值可以是任何类型。
  2. 泛型Dictionary<TKey, TValue> 是泛型集合,允许你指定键和值的类型。
  3. 快速查找Dictionary 使用哈希表实现,因此在大多数情况下,查找、插入和删除操作的时间复杂度接近 O(1)。
  4. 无序Dictionary 中的元素是无序的,如果你需要保持元素的顺序,可以考虑使用其他数据结构,如 List 或 SortedDictionary

声明和初始化

你可以通过以下几种方式声明和初始化一个 Dictionary

using System;  
using System.Collections.Generic;  class Program  
{  static void Main()  {  // 创建一个字典,键为整数,值为字符串  Dictionary<int, string> dictionary = new Dictionary<int, string>();  dictionary.Add(1, "One");  dictionary.Add(2, "Two");  dictionary.Add(3, "Three");  // 使用 foreach 循环遍历字典  foreach (KeyValuePair<int, string> kvp in dictionary)  {  // kvp.Key 获取键,kvp.Value 获取值  Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);  }  }  
}

 

常用操作

  1. 添加元素
dictionary1.Add(4, "Four");
  1. 访问元素
string value = dictionary1[2]; // 通过键访问值
  1. 检查键是否存在
bool containsKey = dictionary1.ContainsKey(1);
  1. 检查值是否存在
bool containsValue = dictionary1.ContainsValue("Two");
  1. 移除元素
dictionary1.Remove(3); // 通过键移除
  1. 遍历元素
foreach (KeyValuePair<int, string> kvp in dictionary1)
{
Console.WriteLine($"Key = {kvp.Key}, Value = {kvp.Value}");
}

示例代码

以下是一个完整的示例,展示了 Dictionary 的基本用法:

using System;  
using System.Collections.Generic;  class Program  
{  static void Main()  {  // 初始化一个 Dictionary  Dictionary<int, string> dictionary = new Dictionary<int, string>  {  { 1, "One" },  { 2, "Two" },  { 3, "Three" }  };  // 添加新的键值对  dictionary.Add(4, "Four");  // 访问并打印元素  foreach (KeyValuePair<int, string> kvp in dictionary)  {  Console.WriteLine($"Key = {kvp.Key}, Value = {kvp.Value}");  }  // 检查键是否存在  if (dictionary.ContainsKey(2))  {  Console.WriteLine("Dictionary contains key 2.");  }  // 移除元素  dictionary.Remove(3);  // 打印移除后的元素  Console.WriteLine("After removal:");  foreach (KeyValuePair<int, string> kvp in dictionary)  {  Console.WriteLine($"Key = {kvp.Key}, Value = {kvp.Value}");  }  }  
}

 KeyValuePair 是一种在 .NET 框架中定义的结构,用于表示一个键值对(Key-Value Pair)。它主要用于集合中,比如字典(Dictionary<TKey, TValue>),以便能够同时访问键(Key)和值(Value)。KeyValuePair 是一种泛型结构,定义在 System.Collections.Generic 命名空间中。

在C#中,$符号用于字符串插值(String Interpolation),它允许你在字符串中嵌入变量或表达式,并且这些变量或表达式会在运行时被其值所替换。这种方式使得字符串的格式化变得更加简洁和直观。 

  • $ 符号告诉编译器,这是一个插值字符串。
  • {kvp.Key} 和 {kvp.Value} 是插值表达式,它们会在运行时被 kvp.Key 和 kvp.Value 的实际值所替换。

 

关键字:sem代运营_企业名称查重_百家港 seo服务_搜索引擎营销例子

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: