在 C# 中如果要將鍵值對(Key-Value Pair)的資料儲存,通常都會使用 Dictionary 來存放。但是 Dictionary 最大的問題就是鍵(Key)不可以重複,不然就會拋出 ArgumentException 例外。
假設我們就是要儲存「鍵值對」的資料,但是是一對多,一個索引對應到多個資料,那就可以使用 ILookup 來儲存。
ILookup 的特性:
參考資料:
Microsoft.Learn - ILookup<TKey,TElement> Interface
Microsoft.Learn - Lookup<TKey,TElement> Class
stack overflow - ILookup interface vs IDictionary
假設我們就是要儲存「鍵值對」的資料,但是是一對多,一個索引對應到多個資料,那就可以使用 ILookup 來儲存。
ILookup 的特性:
- 回傳的內容為 IEnumerable<TElement>
- 唯讀,內容建立後無法改變
- 需要透過 LINQ 建立
var products = new[]
{
new { Category = "飲料", Name = "綠茶" },
new { Category = "飲料", Name = "紅茶" },
new { Category = "點心", Name = "蛋糕" },
new { Category = "點心", Name = "餅乾" },
};
// 轉換為 Lookup ,並指定鍵和值
var lookup = products.ToLookup(p => p.Category, p => p.Name);
foreach (var category in lookup)
{
Console.WriteLine($"Category: {category.Key}");
foreach (var name in category)
{
Console.WriteLine($" Name: {name}");
}
}
參考資料:
Microsoft.Learn - ILookup<TKey,TElement> Interface
Microsoft.Learn - Lookup<TKey,TElement> Class
stack overflow - ILookup interface vs IDictionary
留言
張貼留言
如果有任何問題、建議、想說的話或文章題目推薦,都歡迎留言或來信: a@ruyut.com