簡體   English   中英

在字典C#中搜索字典

[英]searching a dictionary within a dictionary c#

如何檢查以下方案集合是否具有特定的字符串值? 我已經閱讀了幾個類似的示例,但沒有任何幫助。 非常感謝,

我需要的例子

    foreach(var item in data.Valuations)
    {
        if(item.Schemes.Contains("my string")) {
           // Do something 
        }
    }

編碼

    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

我已經使用下面的代碼成功做到了。

    var model = new DetailViewModel 
    {
        model.Data = ...
    }

    // New bit

    model.Data.SelectMany(x => x.Schemes).Where(x => x == "my string");

但是,當查看model.Data時,它尚未應用過濾器。 我想念一些愚蠢的東西嗎? “我的字符串”位於計划中

最有效的方法是使用字典類ContainsKey方法:

if (Values.ContainsKey("my string")) 
{

}

如果您確實想對IEnumerable<String> Schemes屬性進行操作,則只需確保using System.Linq在代碼的頂部,並且.Contains可以完全按照您的問題進行操作。

使用SelectMany嘗試linq:

if(Values.SelectMany(x => x.Value.Keys).Any(x => x == "my string"))
{
   //do your stuff here
}

這將創建內部字典中所有鍵的集合,在此示例中,您可以使用后續查詢進行搜索-使用Any ,如果找到了字符串,則返回true。

您的意思是這樣的嗎:

    if(schemes.Any(x=>x=="my string")) 
    {
       // Do something
    }

您可以使用LINQ中的Any來檢查是否有任何元素匹配謂詞->在這里檢查是否有任何字符串等於“ my string”。

僅當使用Lists ,才可以使用Contains因此其他解決方案是:

public List<string> Schemes
{
    get { return this.Values.Keys.ToList(); }
}

public Dictionary<string, Dictionary<string, double>> Values { get; internal set; }

接着

if(schemes.Contains("my string")) 
{
   // Do something
}

將有效。

但是我建議使用Linq而不是列表中的Contains

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM