首页 > 编程语言 >.NET(C#) LinkedList、Queue<T>和Stack<T>的使用

.NET(C#) LinkedList、Queue<T>和Stack<T>的使用

时间:2023-11-06 23:46:45浏览次数:28  
标签:exe Console LinkedList C# Key Queue Add WriteLine openWith

本文主要介绍.NET(C#)中,LinkedList链表、Queue<T>队列和Stack<T>堆栈的使用,以及相关的示例代码。

1、LinkedList(链表)

链表中元素存储内存中是不连续分配,每个元素都有记录前后节点,节点值可以重复,不能通过下标访问,泛型的使用保证类型安全,可以避免装箱拆箱,找元素就只能遍历,查找不方便,增删比较快。

Console.WriteLine("***************LinkedList<T>******************");
LinkedList<string> linkedList = new LinkedList<string>();
linkedList.AddFirst("C/C++");
linkedList.AddLast("Java");

bool isContain = linkedList.Contains("Java");
LinkedListNode<string> nodeC = linkedList.Find("C/C++");  // 从头查找
linkedList.AddBefore(nodeC, "C#");
linkedList.AddAfter(nodeC, "Python");
foreach(var item in linkedList)
{
  Console.WriteLine("item = "+item);
}
linkedList.Remove("Java");
linkedList.Remove(nodeC);
linkedList.RemoveFirst();
linkedList.RemoveLast();
linkedList.Clear();

2、Queue<T>(队列)

Queue<T>是链表,先进先出,不能通过下标访问,泛型的使用保证类型安全,可以避免装箱拆箱,找元素就只能遍历,查找不方便,增删比较快。

Console.WriteLine("***************Queue******************");
Queue queue = new Queue();
queue.Enqueue("C/C++");
queue.Enqueue("C#");
queue.Enqueue("Java");
queue.Enqueue("Python");
queue.Enqueue("CJavaPy");
queue.Enqueue("JS");
foreach (string item in queue)
{
    Console.WriteLine(item);
}
Console.WriteLine($"Dequeuing '{queue.Dequeue()}'");
Console.WriteLine($"Peek at next item to dequeue: { queue.Peek()}");
Console.WriteLine($"Dequeuing '{queue.Dequeue()}'");
Queue queueCopy = new Queue(queue.ToArray());
foreach (string item in queueCopy)
{
    Console.WriteLine(item);
}
Console.WriteLine($"queueCopy.Contains(\"c#\") = {queueCopy.Contains("c#")}");
queueCopy.Clear();
Console.WriteLine($"queueCopy.Count = {queueCopy.Count}");

注意:ConcurrentQueue 线程安全版本的Queue。

3、Stack<T>(堆栈)

Stack<T>是链表,先进后出,不能通过下标访问,泛型的使用保证类型安全,可以避免装箱拆箱,找元素就只能遍历,查找不方便,增删比较快。

Console.WriteLine("***************Stack******************");
Stack stack = new Stack();
stack.Push("C/C++");
stack.Push("C#");
stack.Push("Java");
stack.Push("Python");
stack.Push("CJavaPy");
stack.Push("JS");
foreach (string item in stack)
{
    Console.WriteLine(item);
}
Console.WriteLine($"Pop '{stack.Pop()}'");//获取并移除
Console.WriteLine($"Peek at next item to dequeue: { stack.Peek()}");//获取不移除
Console.WriteLine($"Pop '{stack.Pop()}'");
Stack stackCopy = new Stack(stack.ToArray());
foreach (string item in stackCopy)
{
    Console.WriteLine(item);
}
Console.WriteLine($"stackCopy.Contains(\"C#\") = {stackCopy.Contains("C#")}");
stackCopy.Clear();
Console.WriteLine($"stackCopy.Count = {stackCopy.Count}");

注意:ConcurrentStack线程安全版本的Stack。

 

4、Dictionary<TKey, TValue>

Dictionary<TKey,TValue>泛型类提供一组键到一组值的映射。 每次对字典的添加都包含一个值和与其关联的键。 使用其键检索值的速度非常快,接近 O (1) ,因为 Dictionary<TKey,TValue> 该类是作为哈希表实现的。检索的速度取决于为指定的类型的哈希算法的质量 TKey 。

// 创建一个新的字符串字典,带有字符串键。            //
Dictionary<string, string> openWith =
    new Dictionary<string, string>();
 
//添加一些元素到字典。没有重复键,但有些值是重复的。
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
 
//如果已经在字典中,则Add方法抛出异常
try
{
    openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
    Console.WriteLine("一个 Key = \"txt\" 的元素已经存在。");
}
 
// Item 属性是索引器的另一个名字,所以访问元素时可以省略其名称。
Console.WriteLine("For key = \"rtf\", value = {0}.",
    openWith["rtf"]);
 
// 索引器可用于更改值
openWith["rtf"] = "winword.exe";
Console.WriteLine("For key = \"rtf\", value = {0}.",
    openWith["rtf"]);
 
// 如果键不存在,则设置该键的索引器 添加一个新的键/值对。
openWith["doc"] = "winword.exe";
 
// 如果请求的键是索引器,则索引器抛出异常
// 不在字典中。
try
{
    Console.WriteLine("For key = \"tif\", value = {0}.",
        openWith["tif"]);
}
catch (KeyNotFoundException)
{
    Console.WriteLine("Key = \"tif\" is not found.");
}
 
// 当一个程序经常不得不尝试结果不是的键时
// 在字典中,TryGetValue 可以更高效获取值的方法。
string value = "";
if (openWith.TryGetValue("tif", out value))
{
    Console.WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
    Console.WriteLine("Key = \"tif\" is not found.");
}
 
// ContainsKey 可用于在插入之前判断key是否存在
if (!openWith.ContainsKey("ht"))
{
    openWith.Add("ht", "hypertrm.exe");
    Console.WriteLine("key = \"ht\": {0}",
        openWith["ht"]);
}
 
//当使用foreach来枚举字典元素时,元素被检索为KeyValuePair对象。
Console.WriteLine();
foreach (KeyValuePair<string, string> kvp in openWith)
{
    Console.WriteLine("Key = {0}, Value = {1}",
        kvp.Key, kvp.Value);
}
 
// 要单独获取值,请使用values属性。
Dictionary<string, string>.ValueCollection valueColl =
    openWith.Values;
 
// ValueCollection的元素是强类型的,具有为字典值指定的类型。
Console.WriteLine();
foreach (string s in valueColl)
{
    Console.WriteLine("Value = {0}", s);
}
 
// 要单独获取键,可使用keys属性。
Dictionary<string, string>.KeyCollection keyColl =
    openWith.Keys;
 
// KeyCollection的元素是强类型的,其类型是为字典键指定的。.
Console.WriteLine();
foreach (string s in keyColl)
{
    Console.WriteLine("Key = {0}", s);
}
 
// 使用Remove方法删除键/值对。
Console.WriteLine("\nRemove(\"doc\")");
openWith.Remove("doc");
 
if (!openWith.ContainsKey("doc"))
{
    Console.WriteLine("Key \"doc\" is not found.");
}

5、SortedDictionary<TKey, TValue>

Dictionary可以使用Linq或者自定义排序,SortDictionary只要插入元素就自动按Key进行了排序。SortedDictionary<TKey,TValue> 需要使用比较器实现来执行键比较。 如果 comparer 为 null ,则此构造函数使用默认的泛型相等比较器Comparer<T>.Default 。 如果类型 TKey 实现 System.IComparable<T> 泛型接口,则默认比较器使用该实现。

SortedDictionary<string, string> openWith =
                      new SortedDictionary<string, string>(
                      StringComparer.CurrentCultureIgnoreCase);
 
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("DIB", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
try
{
    openWith.Add("BMP", "paint.exe");
}
catch (ArgumentException)
{
    Console.WriteLine("\nBMP 已经存在");
}
// 列出排序字典的内容。
Console.WriteLine();
foreach (KeyValuePair<string, string> kvp in openWith)
{
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key,
        kvp.Value);
}

 

6、SortedList<TKey,TValue>

SortedDictionary<TKey, TValue>SortedList<TKey, TValue>的功能相同,都用来存储按Key排序的键值对,且无重复。内部实现的差异却很大,SortedDictionary<TKey, TValue>的内部实现是红黑二叉搜索树,而SortedList<TKey, TValue>的内部是两个数组,分别存储KeyValue序列。SortedList<TKey, TValue>的内存占用的少,但是插入的删除的话数组要比树慢。树是O(log2N),数组是O(N)。插入已排序的数据,SortedList<TKey, TValue>比较快。

// 创建一个新的字符串字典,带有字符串键。            //
SortedList<string, string> openWith =
    new SortedList<string, string>();
//添加一些元素到字典。没有重复键,但有些值是重复的。
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
//如果已经在字典中,则Add方法抛出异常
try
{
    openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
    Console.WriteLine("一个 Key = \"txt\" 的元素已经存在。");
}
// Item 属性是索引器的另一个名字,所以访问元素时可以省略其名称。
Console.WriteLine("For key = \"rtf\", value = {0}.",
    openWith["rtf"]);
// 索引器可用于更改值
openWith["rtf"] = "winword.exe";
Console.WriteLine("For key = \"rtf\", value = {0}.",
    openWith["rtf"]);
// 如果键不存在,则设置该键的索引器 添加一个新的键/值对。
openWith["doc"] = "winword.exe";
// 如果请求的键是索引器,则索引器抛出异常
// 不在字典中。
try
{
    Console.WriteLine("For key = \"tif\", value = {0}.",
        openWith["tif"]);
}
catch (KeyNotFoundException)
{
    Console.WriteLine("Key = \"tif\" is not found.");
}
// 当一个程序经常不得不尝试结果不是的键时
// 在字典中,TryGetValue 可以更高效获取值的方法。
string value = "";
if (openWith.TryGetValue("tif", out value))
{
    Console.WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
    Console.WriteLine("Key = \"tif\" is not found.");
}
// ContainsKey 可用于在插入之前判断key是否存在
if (!openWith.ContainsKey("ht"))
{
    openWith.Add("ht", "hypertrm.exe");
    Console.WriteLine("key = \"ht\": {0}",
        openWith["ht"]);
}
//当使用foreach来枚举字典元素时,元素被检索为KeyValuePair对象。
Console.WriteLine();
foreach (KeyValuePair<string, string> kvp in openWith)
{
    Console.WriteLine("Key = {0}, Value = {1}",
        kvp.Key, kvp.Value);
}
// 要单独获取值,请使用values属性。
IList<string> ilistValues =
    openWith.Values;
// ValueCollection的元素是强类型的,具有为字典值指定的类型。
Console.WriteLine();
foreach (string s in ilistValues)
{
    Console.WriteLine("Value = {0}", s);
}
// 要单独获取键,可使用keys属性。
IList<string> ilistKeys =
    openWith.Keys;
// KeyCollection的元素是强类型的,其类型是为字典键指定的。.
Console.WriteLine();
foreach (string s in ilistKeys)
{
    Console.WriteLine("Key = {0}", s);
}
// 使用Remove方法删除键/值对。
Console.WriteLine("\nRemove(\"doc\")");
openWith.Remove("doc");
if (!openWith.ContainsKey("doc"))
{
    Console.WriteLine("Key \"doc\" is not found.");
}

 

标签:exe,Console,LinkedList,C#,Key,Queue,Add,WriteLine,openWith
From: https://www.cnblogs.com/wwkk/p/17814076.html

相关文章

  • AtCoder Beginner Contest 327
    A-ab题意:判断字符串中是否有“ab”或者是“ba“#include<bits/stdc++.h>usingnamespacestd;voidsolve(){ intn; cin>>n;strings; cin>>s; if(s.find("ab")!=s.npos||s.find("ba")!=s.npos){ cout<<"Yes"; }else{......
  • NSSCTF Round#11 Basic 密码个人赛复盘
    [NSSRound#11Basic]ez_encABAABBBAABABAABBABABAABBABAAAABBABABABAAABAAABBAABBBBABBABBABBABABABAABBAABBABAAABBAABBBABABABAAAABBAAABABAABABBABBBABBAAABBBAABABAABBAAAABBBAAAABAABBBAABBABABAABABAAAAABBBBABAABBBBAAAABBBBBAB第一眼培根密码试了试但不对,观察长度发现应......
  • .NET(C#) Linq GroupBy和GroupJoin的使用
    Linq是LanguageIntegratedQuery的简称,它是微软在.NETFramework3.5里面新加入的特性,用以简化查询查询操作。本文主要介绍.NET(C#)中Linq的GroupBy和GroupJoin操作符1、GroupBy操作符GroupBy操作符类似于SQL语言仲的GruopBy语句,这里的GroupBy操作符用于将输入序列中的元素进......
  • .NET(C#) Cast和OfType的使用
    Linq是LanguageIntegratedQuery的简称,它是微软在.NETFramework3.5里面新加入的特性,用以简化查询查询操作。本文主要介绍.NET(C#)中Linq的Cast和OfType操作符。1、Cast操作符Cast操作符用于将一个类型为IEnumerable的集合对象转换为IEnumerable<T>类型的集合对象。也就是非......
  • .NET(C#) Linq Range和Repeat的使用
    Linq是LanguageIntegratedQuery的简称,它是微软在.NETFramework3.5里面新加入的特性,用以简化查询查询操作。本文主要介绍.NET(C#)中Linq的Range和Repeat操作符。1、Range操作符Range操作符用于辅助生成一个整数序列。usingSystem;usingSystem.Collections.Generic;usi......
  • .NET(C#) 对象的拷贝(浅拷贝和深拷贝)
    本文主要介绍.NET(C#),对象的拷贝,包括浅拷贝和深拷贝,以及浅拷贝和深拷贝的实现方式,不同的实现方式之间的性能对比。1、浅拷贝和深拷贝浅拷贝是指将对象中的数值类型的字段拷贝到新的对象中,而对象中的引用型字段则指复制它的一个引用到目标对象。如果改变目标对象中引用型字段的值......
  • C++模板显示指定类型时使用引用遇到的问题
    1.问题这里我想让模板函数接收int和char类型的参数,并进行相加,显示指定参数类型为int。第一个调用理论上会自动将char类型强转成int类型,后进行相加;第二个调用理论上会自动将int类型强转成char类型,后进行相加;但是报错Nomatchingfunctionforcallto'add_ab'template<typena......
  • HDFS Balancer存储水位稳定性原理与实践
    1.背景在HDFS分布式系统中,经常会上线新的datanode以环境集群容量不足的问题。但是往往旧datanode水位较高,甚至爆满无法写入,新datanode非常空闲,导致旧机器无法写入数据,集群的流量集中到新datanode中,造成新datanode网络延迟。为了解决上述问题,可以通过Balancer工具定时讲高水位dat......
  • 重学C语言——变量及其生命周期
    上一篇blog中,我们写了两个程序,一起来回顾一下~#include<stdio.h>intmain(){ inta=10; printf("%d\n",a); return0;}在这个程序中,我们定义了一个名为a的变量,并申请了4个字节的内存空间,用来存放10这个整数。#include<stdio.h>intmain(){ chara='h'; printf(......
  • USB转串口芯片对比选秀---推荐CP2102和CH340C
    参考应用文章:《USB转串口芯片你看好哪个(USB转串口芯片介绍)》简短不看版:建议选择这2款芯片:CP2102/CP2104和CH340C。稳定性较好。 1.FT232优势:最常用缺点:假货多,并不是不能用,而是稳定性差。串口容易丢。规格书:https://atta.szlcsc.com/upload/public/pdf/source/20130221/14......