简体   繁体   English

如何在C#中将字典的子集提取到另一个字典?

[英]How can I extract a subset of a dictionary into another one in C#?

I want to filter out some dictionary pairs I do not need for further processing. 我想过滤掉一些我不需要进一步处理的字典对。 Check this sample code out: 检查此示例代码:

static void Main(string[] args)
{
    var source = new Dictionary<string, dynamic>();

    source.Add("number", 1);
    source.Add("string1", "One");
    source.Add("string2", "Two");
    source.Add("string3", "Three");

    var onlyStrings = source.Where(s => s.Key != "number").ToDictionary(s => s.Key);
}

In this case, onlyStrings is a Dictionary<string, KeyValuePair<string, object>> 在这种情况下,onlyStrings是Dictionary<string, KeyValuePair<string, object>>

but I want onlyStrings to have the following pairs (a subset of the source dictionary): 但我希望只有字符串具有以下对(源字典的子集):

  • Key: "string1", Value: "One" 键:“string1”,值:“一个”
  • Key: "string2", Value: "Two" 键:“string2”,值:“两个”
  • Key: "string3", Value: "Three" 键:“string3”,值:“三”

What is the best way to get such result? 获得这样结果的最佳方法是什么?

There is an overload to the ToDictionary method that also allows for an elementSelector delegate: ToDictionary方法有一个重载,它也允许一个elementSelector委托:

var onlyStrings = source.Where(s => s.Key != "number")
                        .ToDictionary(dict => dict.Key, dict => dict.Value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何验证一个 xml 是否是 C# 中另一个的子集 - How to verify if one xml is a subset of another in C# 如何使用C#使用字典将位于一个字符串列表中的键映射到位于另一个字符串列表中的值? - How can I use dictionary to map keys located in one string list to values located in another string list using C#? 如何在C#中创建页面以响应另一个页面? - How can I create in C# a page to response to another one? 如何在c#中引用另一个项目? - How can I refer to a project from another one in c#? 如何在C#中订购字典? - How can I order a Dictionary in C#? 如何在 MongoDB C# 驱动程序中获得结果子集? - How can I get a subset of results in MongoDB C# Driver? 如何在C#中从一个分隔符提取子字符串到另一个分隔符? - How to extract a substring from one delimiter to another in C#? 如何检索一行中有字典(C#)的唯一项目的值? - How can I retrieve the value of the only item I have an a Dictionary (C#) in one line? 如何将字典的子集转换为从Dictionary &lt;&gt;派生的类型 - How can I cast a subset of a dictionary to a type derived from Dictionary<> 比较一个最佳列表是否是C#中另一个列表的子集的最佳方法 - Best approach to compare if one list is subset of another in C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM