在C#中,使用LINQ(Language Integrated Query)可以輕松地對字典進行查詢和操作
using System;
using System.Collections.Generic;
using System.Linq;
Dictionary<int, string> myDictionary = new Dictionary<int, string>()
{
{1, "One"},
{2, "Two"},
{3, "Three"},
{4, "Four"},
{5, "Five"}
};
查詢字典中的所有鍵值對:
var allItems = from item in myDictionary
select item;
foreach (var item in allItems)
{
Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
}
查詢字典中鍵大于2的鍵值對:
var filteredItems = from item in myDictionary
where item.Key > 2
select item;
foreach (var item in filteredItems)
{
Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
}
添加一個新的鍵值對到字典中:
myDictionary.Add(6, "Six");
刪除字典中鍵為3的鍵值對:
myDictionary.Remove(3);
更新字典中鍵為2的值:
myDictionary[2] = "TwoUpdated";
var updatedDictionary = filteredItems.ToDictionary(item => item.Key, item => item.Value);
這些示例展示了如何在C#中使用LINQ操作字典。你可以根據(jù)需要修改查詢條件和操作來滿足你的需求。