[英]searching a dictionary within a dictionary c#
How can I check if the following collection of schemes has a certain string value? 如何检查以下方案集合是否具有特定的字符串值? I've read several similar examples but nothing is really helping me.
我已经阅读了几个类似的示例,但没有任何帮助。 Many thanks,
非常感谢,
Example what I need 我需要的例子
foreach(var item in data.Valuations)
{
if(item.Schemes.Contains("my string")) {
// Do something
}
}
The code 编码
public Valuation[] Valuations { get; set; }
public IEnumerable<string> Schemes
{
get { return this.Values.Keys; }
}
public Dictionary<string, Dictionary<string, double>> Values { get; internal set; }
UPDATE UPDATE
I've managed to do it using the following line of code. 我已经使用下面的代码成功做到了。
var model = new DetailViewModel
{
model.Data = ...
}
// New bit
model.Data.SelectMany(x => x.Schemes).Where(x => x == "my string");
However when looking at the model.Data it hasn't applied the filter. 但是,当查看model.Data时,它尚未应用过滤器。 Am I missing something stupid?
我想念一些愚蠢的东西吗? The 'my string' is located in the Schemes
“我的字符串”位于计划中
The most efficient way of doing this is to use the ContainsKey
method of the dictionary class : 最有效的方法是使用字典类的
ContainsKey
方法:
if (Values.ContainsKey("my string"))
{
}
If you really want to operate on your IEnumerable<String> Schemes
property, then you can simply ensure that using System.Linq
is at the top of your code, and .Contains will work exactly as in your question. 如果您确实想对
IEnumerable<String> Schemes
属性进行操作,则只需确保using System.Linq
在代码的顶部,并且.Contains可以完全按照您的问题进行操作。
Try linq with SelectMany
: 使用
SelectMany
尝试linq:
if(Values.SelectMany(x => x.Value.Keys).Any(x => x == "my string"))
{
//do your stuff here
}
This will create a collection of all the keys from the inner dictionaries, which you can search with subsequent queries, in this example - with Any
which will return true if the string was found. 这将创建内部字典中所有键的集合,在此示例中,您可以使用后续查询进行搜索-使用
Any
,如果找到了字符串,则返回true。
Do you mean something like this: 您的意思是这样的吗:
if(schemes.Any(x=>x=="my string"))
{
// Do something
}
you can use Any
from LINQ to check if there is any element matching predicate -> here checking if there is any string equals to "my string". 您可以使用LINQ中的
Any
来检查是否有任何元素匹配谓词->在这里检查是否有任何字符串等于“ my string”。
You can use Contains
only if using Lists
so other solution is: 仅当使用
Lists
,才可以使用Contains
因此其他解决方案是:
public List<string> Schemes
{
get { return this.Values.Keys.ToList(); }
}
public Dictionary<string, Dictionary<string, double>> Values { get; internal set; }
and then 接着
if(schemes.Contains("my string"))
{
// Do something
}
will be valid. 将有效。
BUT I suggest using Linq instead of Contains
on list. 但是我建议使用Linq而不是列表中的
Contains
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.