C#常用数据存储

C#常用数据存储类型

1.List<T> 类

表示可通过索引访问的对象的强类型列表。 提供用于对列表进行搜索、排序和操作的方法。

命名空间:  System.Collections.Generic
程序集:  mscorlib(在 mscorlib.dll 中)

public class List<T> : IList<T>, ICollection<T>, 
	IEnumerable<T>, IList, ICollection, IEnumerable
构造函数

List<T>() :初始化 List<T> 类的新实例,该实例为空并且具有默认初始容量。

属性

Capacity:获取或设置该内部数据结构在不调整大小的情况下能够容纳的元素总数。
Count:获取 List<T> 中实际包含的元素数。
Item :获取或设置指定索引处的元素。

方法
Add 将对象添加到 List<T> 的结尾处。

Clear:从 List<T> 中移除所有元素。

ForEach:对 List<T> 的每个元素执行指定操作。

ForEach:对 List<T> 的每个元素执行指定操作。

Insert:将元素插入 List<T> 的指定索引处。

Remove:从 List<T> 中移除特定对象的第一个匹配项。

实例代码

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        List<string> dinosaurs = new List<string>();

        Console.WriteLine("\nCapacity: {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("\nCapacity: {0}", dinosaurs.Capacity);
        Console.WriteLine("Count: {0}", dinosaurs.Count);

        Console.WriteLine("\nContains(\"Deinonychus\"): {0}",
            dinosaurs.Contains("Deinonychus"));

        Console.WriteLine("\nInsert(2, \"Compsognathus\")");
        dinosaurs.Insert(2, "Compsognathus");

        Console.WriteLine();
        foreach(string dinosaur in dinosaurs)
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\ndinosaurs[3]: {0}", dinosaurs[3]);

        Console.WriteLine("\nRemove(\"Compsognathus\")");
        dinosaurs.Remove("Compsognathus");

        Console.WriteLine();
        foreach(string dinosaur in dinosaurs)
        {
            Console.WriteLine(dinosaur);
        }
 }
}

2.ArrayList 类

使用大小会根据需要动态增加的数组来实现 IList 接口。

命名空间:   System.Collections
程序集:  mscorlib(位于 mscorlib.dll)

构造函数
ArrayList():初始化 ArrayList 类的新实例,该实例为空并且具有默认初始容量。

属性
Capacity:获取或设置 ArrayList 可包含的元素数。
Count:获取 ArrayList 中实际包含的元素数。

方法
Add(Object):将对象添加到 ArrayList 的结尾处。
AddRange(ICollection):将 ICollection 的元素添加到 ArrayList 的末尾。

Clear():从 ArrayList 中移除所有元素。

GetType():获取当前实例的 Type。(继承自 Object。)

IndexOf(Object):搜索指定 Object 并返回整个内的第一个匹配项的从零开始索引 ArrayList。

Remove(Object):从 ArrayList 中移除特定对象的第一个匹配项。

ToString():返回表示当前对象的字符串。(继承自 Object。)

示例代码

using System;
using System.Collections;
public class SamplesArrayList  {

   public static void Main()  {

      // Creates and initializes a new ArrayList.
      ArrayList myAL = new ArrayList();
      myAL.Add("Hello");
      myAL.Add("World");
      myAL.Add("!");

      // Displays the properties and values of the ArrayList.
      Console.WriteLine( "myAL" );
      Console.WriteLine( "    Count:    {0}", myAL.Count );
      Console.WriteLine( "    Capacity: {0}", myAL.Capacity );
      Console.Write( "    Values:" );
      PrintValues( myAL );
   }

   public static void PrintValues( IEnumerable myList )  {
      foreach ( Object obj in myList )
         Console.Write( "   {0}", obj );
      Console.WriteLine();
   }

}



/* 
This code produces output similar to the following:

myAL
    Count:    3
    Capacity: 4
    Values:   Hello   World   !

*/

3.Dictionary<TKey, TValue> 类

表示键和值的集合。

命名空间:   System.Collections.Generic
程序集:  mscorlib(位于 mscorlib.dll)

类型参数
TKey:字典中的键的类型。
TValue:字典中的值的类型。

构造函数

Dictionary<TKey, TValue>()
初始化 Dictionary<TKey, TValue> 类的新实例,该实例为空,具有默认的初始容量并为键类型使用默认的相等比较器。

属性

Count获取包含在 Dictionary<TKey, TValue> 中的键/值对的数目。

Item[TKey]:获取或设置与指定的键关联的值。
Keys :获得一个包含 Dictionary<TKey, TValue> 中的键的集合。
Values:获得一个包含 Dictionary<TKey, TValue> 中的值的集合。

方法
Add(TKey, TValue) :将指定的键和值添加到字典中。
Clear():将所有键和值从 Dictionary<TKey, TValue> 中移除。

GetType():获取当前实例的 Type。(继承自 Object。)

Remove(TKey):将带有指定键的值从 Dictionary<TKey, TValue> 中移除。
ToString():返回表示当前对象的字符串。(继承自 Object。)

示例代码

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // 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.
        // 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");

        // The Add method throws an exception if the new key is 
        // already in the dictionary.
        // already in the 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. 
        // can omit its name when accessing elements. 
        Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);

        // The indexer can be used to change the value associated
        // with a key.
        // with a key.
        openWith["rtf"] = "winword.exe";
        Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);

        // If a key does not exist, setting the indexer for that key
        // adds a new key/value pair.
        // adds a new key/value pair.
        openWith["doc"] = "winword.exe";

        // The indexer throws an exception if the requested key is not in the dictionary.
        try
        {
            Console.WriteLine("For key = \"tif\", value = {0}.", openWith["tif"]);
        }
        catch (KeyNotFoundException)
        {
            Console.WriteLine("Key = \"tif\" is not found.");
        }

        // When a program often has to try keys that turn out not to
        // be in the dictionary, TryGetValue can be a more efficient 
        // way to retrieve values.
        // be in the dictionary, TryGetValue can be a more efficient 
        // way to retrieve values.
        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("\nRemove(\"doc\")");
        openWith.Remove("doc");

        if (!openWith.ContainsKey("doc"))
        {
            Console.WriteLine("Key \"doc\" is not found.");
        }
    }
}

/* This code example produces the following output:

An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
Key = "tif" is not found.
Key = "tif" is not found.
Value added for key = "ht": hypertrm.exe

Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = rtf, Value = winword.exe
Key = doc, Value = winword.exe
Key = ht, Value = hypertrm.exe

Value = notepad.exe
Value = paint.exe
Value = paint.exe
Value = winword.exe
Value = winword.exe
Value = hypertrm.exe

Key = txt
Key = bmp
Key = dib
Key = rtf
Key = doc
Key = ht

Remove("doc")
Key "doc" is not found.
 */
  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值