首頁  >  文章  >  後端開發  >  C# 中列表和字典有什麼差別?

C# 中列表和字典有什麼差別?

王林
王林轉載
2023-08-27 15:57:101269瀏覽

C# 中列表和字典有什么区别?

字典是 C# 中鍵和值的集合。 Dictionary 包含在 System.Collection.Generics 命名空間中。 Dictionary 是一個泛型類型,如果您嘗試尋找不存在的鍵,則會傳回錯誤。

List 集合是一個泛型類,可以儲存任何資料類型來建立清單。

清單是一組項目 -
List<string> myList = new List<string>() {
   "Maths",
   "English",
"   Science"
};

字典是一組鍵值對。

Dictionary<string, int> d = new Dictionary<string, int>();

d.Add("squash", 1);
d.Add("football", 2);
d.Add("rugby", 3);

在清單中循環更容易、更快,並且可以透過清單輕鬆使用索引存取元素。

以上是C# 中列表和字典有什麼差別?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除