【C#】【集合】

82 阅读1分钟

基于IList 或者直接基于ICollection 的集合

常用的集合类型 - .NET | Microsoft Learn

List

与JAVA中List类似,但不需要List实现类,本身就可以使用。

var names = new List<string> { "<name>", "Ana", "Felipe"};
names.Add("Maria");
names.Add("Bill");
names.Remove("Ana");

names.Sort();

var index = names.IndexOf("Felipe");
var notFound = names.IndexOf("Not found");
Console.WriteLine(notFound);
foreach (var name in names)
{
    Console.WriteLine(name.ToUpper());
}
Console.WriteLine($"My name is {names[0]}");
Console.WriteLine($"This list has {names.Count} names");


var fibonacciNumbers = new List<int> {1, 1};
for(int i = 3; i <= 20;i++)
{
    var previous = fibonacciNumbers[fibonacciNumbers.Count - 1];
    var previous2 = fibonacciNumbers[fibonacciNumbers.Count -2];
    fibonacciNumbers.Add(previous+previous2);
}
Console.WriteLine(fibonacciNumbers[fibonacciNumbers.Count-1]);

Array

与JAVA类似,长度固定。 Array Class (System) | Microsoft Learn

ArrayList

不建议使用 ArrayList 类进行新开发。 建议改用List 类.类旨在保存对象的异类集合。

LinkedList

LinkedList<string> countries = new LinkedList<string>();
countries.AddFirst("China");
countries.AddLast("America");
var current = countries.FindLast("China");
if (current != null)
{
    countries.AddAfter(current,"Japan");
}
foreach (var country in countries)
{
    Console.WriteLine(country);
}

Queue

不建议使用 Queue 类进行新的开发。 建议改用泛型Queue<T>类。

Queue<>

Queue<string> countries = new Queue<string>();
countries.Enqueue("China");
countries.Enqueue("America");
var current = countries.Dequeue();
if (current != null)
{
    Console.WriteLine(current);
}
foreach (var country in countries)
{
    Console.WriteLine(country);
}

Stack<>

不建议使用 Stack 类进行新的开发。 建议改用泛型System.Collections.Generic.Stack类。

using System.Collections.Generic;
Stack<String> numbers = new Stack<String>();
numbers.Push("one");
numbers.Push("two");
numbers.Push("three");
var current = numbers.Pop();
if(current != null)
{
    Console.WriteLine(current);
}
current = numbers.Peek();
if(current != null)
{
    Console.WriteLine(current);
}

基于ICictionary接口的集合

每个元素包含一个键和一个值。

Dictionary<>

using System.Collections.Generic;
Dictionary<string,string> openWith = new Dictionary<string,string>();
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp","paint.exe");
openWith.Add("dib","paint.exe");

foreach (var item in openWith)
{
    Console.WriteLine(item.Key);
    Console.WriteLine(item.Value);

}
openWith.Remove("bmp");

SortedList<>

  • SortedList<TKey,TValue>使用的内存少于SortedDictionary<TKey,TValue>;

  • [SortedDictionary<TKey,TValue>]对于未排序的数据,O ( n) 具有更快的插入和删除操作,而不是 O[SortedList<TKey,TValue>(n)]。

  • 对key进行排序,要求key实现比较器这个接口,如果未实现,可以在构造函数中指定实现的比较器。

    using System.Collections.Generic;
SortedList<string,string> openWith = new SortedList<string,string>();
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp","paint.exe");
openWith.Add("dib","paint.exe");

foreach (var item in openWith)
{
    Console.WriteLine(item.Key);
    Console.WriteLine(item.Value);

}
openWith.Remove("bmp");