如何使用LINQ操作C#字典

1949idc 2年前 (2024-09-19) 阅读数 309 #编程语言

在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操作字典。你可以根据需要修改查询条件和操作来满足你的需求。

版权声明

本文内容由互联网用户自发贡献,该文观点仅代表作者本人
本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

© 2010 首途云安 & 厦门硕顿信息技术有限公司 & 闽ICP备11016866号  增值电信业务经营许可证:B1-20203020 地址:福建厦门思明区嘉禾路297号1806
高新技术企业
软件产品证书
计算机软件著作权
ISO认证
国家3A企业