温馨提示×

如何使用LINQ操作C#字典

c#
小樊
83
2024-09-11 10:32:24
栏目: 编程语言

在C#中,使用LINQ(Language Integrated Query)可以轻松地对字典进行查询和操作

  1. 引入命名空间:
using System;
using System.Collections.Generic;
using System.Linq;
  1. 创建一个字典实例:
Dictionary<int, string> myDictionary = new Dictionary<int, string>()
{
    {1, "One"},
    {2, "Two"},
    {3, "Three"},
    {4, "Four"},
    {5, "Five"}
};
  1. 使用LINQ查询字典:

查询字典中的所有键值对:

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}");
}
  1. 使用LINQ操作字典:

添加一个新的键值对到字典中:

myDictionary.Add(6, "Six");

删除字典中键为3的键值对:

myDictionary.Remove(3);

更新字典中键为2的值:

myDictionary[2] = "TwoUpdated";
  1. 将LINQ查询结果转换为字典:
var updatedDictionary = filteredItems.ToDictionary(item => item.Key, item => item.Value);

这些示例展示了如何在C#中使用LINQ操作字典。你可以根据需要修改查询条件和操作来满足你的需求。

0