表示可通过索引访问的对象的强类型列表。提供用于对列表进行搜索、排序和操作的方法。
public
static
void
ListTest()
... {
List<string> dinosaurs = new List<string>();
Console.WriteLine(" Capacity: {0}", dinosaurs.Capacity);
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");
Console.WriteLine();
foreach (string dinosaur in dinosaurs)
...{
Console.WriteLine(dinosaur);
}
Console.WriteLine(" Capacity: {0}", dinosaurs.Capacity);
Console.WriteLine("Count: {0}", dinosaurs.Count);
Console.WriteLine(" Contains("Deinonychus"): {0}",
dinosaurs.Contains("Deinonychus"));
Console.WriteLine(" Insert(2, "Compsognathus")");
dinosaurs.Insert(2, "Compsognathus");
Console.WriteLine();
foreach (string dinosaur in dinosaurs)
...{
Console.WriteLine(dinosaur);
}
Console.WriteLine(" dinosaurs[3]: {0}", dinosaurs[3]);
Console.WriteLine(" Remove("Compsognathus")");
dinosaurs.Remove("Compsognathus");
Console.WriteLine();
foreach (string dinosaur in dinosaurs)
...{
Console.WriteLine(dinosaur);
}
dinosaurs.TrimExcess();
Console.WriteLine(" TrimExcess()");
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
Console.WriteLine("Count: {0}", dinosaurs.Count);
dinosaurs.Clear();
Console.WriteLine(" Clear()");
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
Console.WriteLine("Count: {0}", dinosaurs.Count);
}
... {
List<string> dinosaurs = new List<string>();
Console.WriteLine(" Capacity: {0}", dinosaurs.Capacity);
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");
Console.WriteLine();
foreach (string dinosaur in dinosaurs)
...{
Console.WriteLine(dinosaur);
}
Console.WriteLine(" Capacity: {0}", dinosaurs.Capacity);
Console.WriteLine("Count: {0}", dinosaurs.Count);
Console.WriteLine(" Contains("Deinonychus"): {0}",
dinosaurs.Contains("Deinonychus"));
Console.WriteLine(" Insert(2, "Compsognathus")");
dinosaurs.Insert(2, "Compsognathus");
Console.WriteLine();
foreach (string dinosaur in dinosaurs)
...{
Console.WriteLine(dinosaur);
}
Console.WriteLine(" dinosaurs[3]: {0}", dinosaurs[3]);
Console.WriteLine(" Remove("Compsognathus")");
dinosaurs.Remove("Compsognathus");
Console.WriteLine();
foreach (string dinosaur in dinosaurs)
...{
Console.WriteLine(dinosaur);
}
dinosaurs.TrimExcess();
Console.WriteLine(" TrimExcess()");
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
Console.WriteLine("Count: {0}", dinosaurs.Count);
dinosaurs.Clear();
Console.WriteLine(" Clear()");
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
Console.WriteLine("Count: {0}", dinosaurs.Count);
}
表示键和值的集合。
public
static
void
DictionaryTest()
... {
// Create a new dictionary of strings, with string keys.
//
Dictionary<string, string> openWith =
new Dictionary<string, string>();
// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
// 向Dictionary中添加已经存在的键值会报异常
try
...{
openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
...{
Console.WriteLine("An element with Key = "txt" already exists.");
}
// The Item property is another name for the indexer, so you
// can omit its name when accessing elements.
//
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 can be used to test keys before inserting
// them.
if (!openWith.ContainsKey("ht"))
...{
openWith.Add("ht", "hypertrm.exe");
Console.WriteLine("Value added for key = "ht": {0}",
openWith["ht"]);
}
// When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
Console.WriteLine();
foreach (KeyValuePair<string, string> kvp in openWith)
...{
Console.WriteLine("Key = {0}, Value = {1}",
kvp.Key, kvp.Value);
}
// To get the values alone, use the Values property.
Dictionary<string, string>.ValueCollection valueColl =
openWith.Values;
// The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
Console.WriteLine();
foreach (string s in valueColl)
...{
Console.WriteLine("Value = {0}", s);
}
// To get the keys alone, use the Keys property.
Dictionary<string, string>.KeyCollection keyColl =
openWith.Keys;
// The elements of the KeyCollection are strongly typed
// with the type that was specified for dictionary keys.
Console.WriteLine();
foreach (string s in keyColl)
...{
Console.WriteLine("Key = {0}", s);
}
// Use the Remove method to remove a key/value pair.
Console.WriteLine(" Remove("doc")");
openWith.Remove("doc");
if (!openWith.ContainsKey("doc"))
...{
Console.WriteLine("Key "doc" is not found.");
}
}
... {
// Create a new dictionary of strings, with string keys.
//
Dictionary<string, string> openWith =
new Dictionary<string, string>();
// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
// 向Dictionary中添加已经存在的键值会报异常
try
...{
openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
...{
Console.WriteLine("An element with Key = "txt" already exists.");
}
// The Item property is another name for the indexer, so you
// can omit its name when accessing elements.
//
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 can be used to test keys before inserting
// them.
if (!openWith.ContainsKey("ht"))
...{
openWith.Add("ht", "hypertrm.exe");
Console.WriteLine("Value added for key = "ht": {0}",
openWith["ht"]);
}
// When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
Console.WriteLine();
foreach (KeyValuePair<string, string> kvp in openWith)
...{
Console.WriteLine("Key = {0}, Value = {1}",
kvp.Key, kvp.Value);
}
// To get the values alone, use the Values property.
Dictionary<string, string>.ValueCollection valueColl =
openWith.Values;
// The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
Console.WriteLine();
foreach (string s in valueColl)
...{
Console.WriteLine("Value = {0}", s);
}
// To get the keys alone, use the Keys property.
Dictionary<string, string>.KeyCollection keyColl =
openWith.Keys;
// The elements of the KeyCollection are strongly typed
// with the type that was specified for dictionary keys.
Console.WriteLine();
foreach (string s in keyColl)
...{
Console.WriteLine("Key = {0}", s);
}
// Use the Remove method to remove a key/value pair.
Console.WriteLine(" Remove("doc")");
openWith.Remove("doc");
if (!openWith.ContainsKey("doc"))
...{
Console.WriteLine("Key "doc" is not found.");
}
}
双向链表,.NET Framework 2.0 版中是新增的。
public
static
void
LinkListTest()
... {
string[] words =
...{ "the", "fox", "jumped", "over", "the", "dog" };
LinkedList<string> sentence = new LinkedList<string>(words);
Display(sentence);
Console.WriteLine("sentence.Contains("jumped") = {0}",
sentence.Contains("jumped"));
// Add the word "today" to the beginning of the linked list.
// Remove the new node, and add it to the end of the list.
sentence.AddFirst("today");
Display(sentence);
LinkedListNode<string> mark1 = sentence.First;
sentence.RemoveFirst();
sentence.AddLast(mark1);
Display(sentence);
sentence.RemoveLast();
sentence.AddLast("yesterday");
Display(sentence);
mark1 = sentence.Last;
sentence.RemoveLast();
sentence.AddFirst(mark1);
Display(sentence);
sentence.RemoveFirst();
LinkedListNode<string> current = sentence.FindLast("the");
DisplayNode(current);
sentence.AddAfter(current, "old");
sentence.AddAfter(current, "lazy");
DisplayNode(current);
current = sentence.Find("fox");
DisplayNode(current);
sentence.AddBefore(current, "quick");
sentence.AddBefore(current, "brown");
DisplayNode(current);
// Keep a reference to the current node, "fox", and to the
// previous node in the list. Use the Find method to locate
// the node containing the value "dog". Show the position.
mark1 = current;
LinkedListNode<string> mark2 = current.Previous;
current = sentence.Find("dog");
DisplayNode(current);
// The AddBefore method throws an InvalidOperationException
// if you try to add a node that already belongs to a list.
try
...{
sentence.AddBefore(current, mark1);
}
catch (InvalidOperationException ex)
...{
Console.WriteLine("Exception message: {0}", ex.Message);
}
// Remove the node referred to by mark1, and add it before
// the node referred to by current. Show the sentence,
// highlighting the position of the node referred to by
// current.
sentence.Remove(mark1);
sentence.AddBefore(current, mark1);
DisplayNode(current);
// Remove the node referred to by current. If you try to show
// its position now, the DisplayNode method prints a message.
// Add the node after the node referred to by mark2, and
// display the sentence, highlighting current.
sentence.Remove(current);
DisplayNode(current);
sentence.AddAfter(mark2, current);
DisplayNode(current);
// The Remove method finds and removes the first node that
// that has the specified value.
sentence.Remove("old");
Display(sentence);
// When the linked list is cast to ICollection(Of String),
// the Add method adds a node to the end of the list.
sentence.RemoveLast();
ICollection<string> icoll = sentence;
icoll.Add("rhinoceros");
Display(sentence);
// Create an array with the same number of elements as the
// linked list.
Console.WriteLine(" Copy the list to an array.");
string[] sArray = new string[sentence.Count];
sentence.CopyTo(sArray, 0);
foreach (string s in sArray)
...{
Console.WriteLine(s);
}
// Release all the nodes.
sentence.Clear();
}
private static void Display(LinkedList < string > words)
... {
foreach (string word in words)
...{
Console.Write(word + " ");
}
Console.WriteLine();
}
// 在找到节点上加()
private static void DisplayNode(LinkedListNode < string > node)
... {
if (node.List == null)
...{
Console.WriteLine("Node "{0}" is not in a list.",
node.Value);
return;
}
StringBuilder result = new StringBuilder("(" + node.Value + ")");
LinkedListNode<string> nodeP = node.Previous;
while (nodeP != null)
...{
result.Insert(0, nodeP.Value + " ");
nodeP = nodeP.Previous;
}
node = node.Next;
while (node != null)
...{
result.Append(" " + node.Value);
node = node.Next;
}
Console.WriteLine(result);
}
... {
string[] words =
...{ "the", "fox", "jumped", "over", "the", "dog" };
LinkedList<string> sentence = new LinkedList<string>(words);
Display(sentence);
Console.WriteLine("sentence.Contains("jumped") = {0}",
sentence.Contains("jumped"));
// Add the word "today" to the beginning of the linked list.
// Remove the new node, and add it to the end of the list.
sentence.AddFirst("today");
Display(sentence);
LinkedListNode<string> mark1 = sentence.First;
sentence.RemoveFirst();
sentence.AddLast(mark1);
Display(sentence);
sentence.RemoveLast();
sentence.AddLast("yesterday");
Display(sentence);
mark1 = sentence.Last;
sentence.RemoveLast();
sentence.AddFirst(mark1);
Display(sentence);
sentence.RemoveFirst();
LinkedListNode<string> current = sentence.FindLast("the");
DisplayNode(current);
sentence.AddAfter(current, "old");
sentence.AddAfter(current, "lazy");
DisplayNode(current);
current = sentence.Find("fox");
DisplayNode(current);
sentence.AddBefore(current, "quick");
sentence.AddBefore(current, "brown");
DisplayNode(current);
// Keep a reference to the current node, "fox", and to the
// previous node in the list. Use the Find method to locate
// the node containing the value "dog". Show the position.
mark1 = current;
LinkedListNode<string> mark2 = current.Previous;
current = sentence.Find("dog");
DisplayNode(current);
// The AddBefore method throws an InvalidOperationException
// if you try to add a node that already belongs to a list.
try
...{
sentence.AddBefore(current, mark1);
}
catch (InvalidOperationException ex)
...{
Console.WriteLine("Exception message: {0}", ex.Message);
}
// Remove the node referred to by mark1, and add it before
// the node referred to by current. Show the sentence,
// highlighting the position of the node referred to by
// current.
sentence.Remove(mark1);
sentence.AddBefore(current, mark1);
DisplayNode(current);
// Remove the node referred to by current. If you try to show
// its position now, the DisplayNode method prints a message.
// Add the node after the node referred to by mark2, and
// display the sentence, highlighting current.
sentence.Remove(current);
DisplayNode(current);
sentence.AddAfter(mark2, current);
DisplayNode(current);
// The Remove method finds and removes the first node that
// that has the specified value.
sentence.Remove("old");
Display(sentence);
// When the linked list is cast to ICollection(Of String),
// the Add method adds a node to the end of the list.
sentence.RemoveLast();
ICollection<string> icoll = sentence;
icoll.Add("rhinoceros");
Display(sentence);
// Create an array with the same number of elements as the
// linked list.
Console.WriteLine(" Copy the list to an array.");
string[] sArray = new string[sentence.Count];
sentence.CopyTo(sArray, 0);
foreach (string s in sArray)
...{
Console.WriteLine(s);
}
// Release all the nodes.
sentence.Clear();
}
private static void Display(LinkedList < string > words)
... {
foreach (string word in words)
...{
Console.Write(word + " ");
}
Console.WriteLine();
}
// 在找到节点上加()
private static void DisplayNode(LinkedListNode < string > node)
... {
if (node.List == null)
...{
Console.WriteLine("Node "{0}" is not in a list.",
node.Value);
return;
}
StringBuilder result = new StringBuilder("(" + node.Value + ")");
LinkedListNode<string> nodeP = node.Previous;
while (nodeP != null)
...{
result.Insert(0, nodeP.Value + " ");
nodeP = nodeP.Previous;
}
node = node.Next;
while (node != null)
...{
result.Append(" " + node.Value);
node = node.Next;
}
Console.WriteLine(result);
}