泛型集合List
相信大家有用過List的都知道他的魔力,Generic 這個類別是從C#2.0所新增的類別,在C# 3.0的又多了更強大的功能。讓我們可以更輕鬆更偷懶的寫出比2.0少寫幾行Code的敘述句。我簡單的紀錄一下以免我又忘記怎麼使用了。
使用List前要記得先引用 using System.Collections.Generic;
首先我們要介紹建立建構函式
以往2.0的寫法
public class Products
{
private int id;
public int ID
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private double unitprice;
public double UnitPrice
{
get { return unitprice; }
set { unitprice = value; }
}
}
C# 3.0的寫法
public class Products
{
public int ID { get; set; }
public string Name { get; set; }
public double UnitPrice { get; set; }
}
C#3.0的敘述 是不是簡短許多呢!
介紹一下 解構函式他是用來解構類別用的
那一個類別只允許有一個解構函式,不能被繼承跟多載,他不能被主動呼叫,會自動叫用。
~Products()
{
MessageBox.Show("已經解構!");
}
看一下MSDN有解釋一段
C# 並不需要太多的記憶體管理動作。這是因為 .NET Framework 記憶體回收行程隱含管理您物件的記憶體配置和釋放。但是,當您的應用程式封裝 Unmanaged 資源 (例如視窗、檔案和網路連線) 時,則您應使用解構函式來釋放這些資源。當物件符合解構資格時,記憶體回收行程便會執行該物件的 Finalize 方法。
所以C#不用去呼叫解構子他會自動去解構!
接下來我們將建立List<Products>
//C# 2.0
List<Products> products = new List<Products>();
//Add是將該item加到List的最後一個item
products.Add(new Products(1, "螺絲", 3.6));
products.Add(new Products(2, "螺帽", 4.2));
//C#3.0
List<Products> pList = new List<Products>
{
new Products{ ID = 1 , Name = "螺絲" , UnitPrice = 3.6},
new Products{ ID = 2 , Name = "螺帽" , UnitPrice = 4.2},
new Products{ ID = 3 , Name = "銅片" , UnitPrice = 5.4},
new Products{ ID = 4 , Name = "鋼釘" , UnitPrice = 2.4},
new Products{ ID = 5 , Name = "鐵釘" , UnitPrice = 1.5}
};
使用Count擴充方法須引用Linq 找尋UnitPrice大於3的筆數
//3
int numberUnitPrice = pList.Count(p => p.UnitPrice > 3);
//3
int numberCategoryID = pList.Count(p => p.CategoryID == 1);
使用FindAll找到UnitPirce大於2
List<Products> psubList = pList.FindAll(EndsUnitPrice);
private static bool EndsUnitPrice(Products p)
{
if (p.UnitPrice > 2)
return true;
else
return false;
}
排序
//C#2.0使用List<T>.sort的方法來排序資料
pList.Sort(delegate(Products p1, Products p2)
{
//使用委派
return p1.UnitPrice.CompareTo(p2.UnitPrice);
});
//dataGridView1.DataSource = pList;
使用擴充方法OrderBy<(Of <(TSource, TKey>)>)(IEnumerable<(Of <(TSource>)>), Func<(Of <(TSource, TKey>)>)) 來排序序列的項目。
//由小到大排序
IEnumerable<Products> pd1 = pList.OrderBy(p => p.UnitPrice);
//由大到小排序
IEnumerable<Products> pd2 = pList.OrderByDescending(p => p.UnitPrice);
//dataGridView1.DataSource = pd1.ToList();
條件式查詢
//UnitPrice > 2
IEnumerable<Products> pd3 = pList.Where(p => p.UnitPrice > 2);
var pdUnitPrice = pList.Select((p, index) => new { index, p.Name });
//dataGridView1.DataSource = pdUnitPrice.ToList();
當然還有很多東西可以使用大家可以上MSDN自己挖寶囉!
參考資料來源:IEnumerable介面