[C#.NET][VB.NET] 泛型集合 Generic Collection - List<> 集合 類別簡介

  • 15999
  • 0
  • C#
  • 2009-06-11

[C#.NET][VB.NET] 泛型集合 Generic Collection - List<> 集合 類別簡介
List 類別是泛型的集合,它位於 System.Collections.Generic 命名空間 裡;

其特性如下:

1.它對應到一般集合ArrayList,但它功能更具彈性。[C#.NET][VB.NET] 一般集合 - ArrayList 類別 排序

2.利用索引號對應內容,索引號由零開始升冪,就跟陣列一樣。

續上一篇[C#.NET][VB.NET] 一般 / 泛型 Generic Collection 集合型別介紹

List 類別是泛型的集合,它位於 System.Collections.Generic 命名空間 裡;

其特性如下:

1.它對應到一般集合ArrayList,但它功能更具彈性。[C#.NET][VB.NET] 一般集合 - ArrayList 類別 排序

2.利用索引號對應內容,索引號由零開始升冪,就跟陣列一樣。

快照-200948175126

如何使用泛型List<>集合

1.引用List<>類別集合,並在<>中賦予引用資料型態。
List<string> myList = new List<string>();

 

 

 
2.加入內容(Value)。
myList.Add("one");
myList.Add("three");
myList.Add("two");

 

 

 

 

 

如何列出List<>集合

利用ForEach方法及匿名委派

myList.ForEach(delegate(string str)
{
    Console.WriteLine(str);
}
);

 

 

 

利用foreach

foreach (string d in myList)
{
    Console.WriteLine(d);
}

 

 

 

C#完整範例

private void button1_Click(object sender, EventArgs e)
{
    //1.引用List<>類別集合,並在<>中賦予引用資料型態。
    List<string> myList = new List<string>();
    //2.加入內容(Value)。
    myList.Add("one");
    myList.Add("three");
    myList.Add("two");
    //如何列出List<>集合
    foreach (string d in myList)
    {
        Console.WriteLine(d);
    }
    Console.WriteLine("index1: " + myList[1].ToString());
    //如何列出List<>集合
    myList.ForEach(delegate(string str)
    {
        Console.WriteLine(str);
    }
    );
}

 

 

 

VB完整範例

 

VB似乎沒有匿名方法

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    '1.引用List<>類別集合,並在<>中賦予引用資料型態。
    Dim myList As New List(Of String)()
    '2.加入內容(Value)。
    myList.Add("one")
    myList.Add("three")
    myList.Add("two")
    '如何列出List<>集合
    For Each d As String In myList
        Console.WriteLine(d)
    Next
    myList.ForEach(AddressOf delmethod)
End Sub
Sub delmethod(ByVal str As String)
    Console.WriteLine(str)
End Sub

 

範例下載:Generic-List.rar

 

 

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo