[英]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): 但我希望只有字符串具有以下对(源字典的子集):
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.