简体   繁体   English

遍历字典 c# 中的值列表

[英]Iterating through list of values in a dictionary c#

I have a dictionary defined as below ,我有一本字典定义如下,

Dictionary<string, List<string>> dictionaryValues = new Dictionary<string, List<string>>();

Since I have a List of values I want iterate through them and find out what values have ="true" in them Here is the source code what I have tried thus far由于我有一个值列表,我想遍历它们并找出其中包含“true”的值 这是我迄今为止尝试过的源代码

Would appreciate any help on this将不胜感激在这方面的任何帮助

List<string> listValues = new List<string>();

listValues.Add("value=true");

listValues.Add("value=false");

dictionaryValues.Add("Name", listValues);

            foreach (var item in dictionaryValues)
            {
                foreach (var item in item.Value)
                {
                    if (item.Contains("true"))
                    {

                    }
                }
            }

You can use the Values property on the dictionary.您可以使用字典上的 Values 属性。 Also, you'll have to rename one of the "item" variables in either of the foreach loops.此外,您必须重命名任一 foreach 循环中的“项目”变量之一。

See also msdn here .另请参阅此处的msdn。

foreach (List<string> items in dictionaryValues.Values)
{
  foreach (string item in items)
  {
     if (item.Contains("true"))
     {
     }
  }
}

I've also made it explicit what types the "items" and "item" are for clarity.为了清楚起见,我还明确说明了“项目”和“项目”的类型。

通过使用 Linq,您可以使用 SelectMany 和 Where 执行此操作:

 var valuesWithTrue =  dictionaryValues.Values.SelectMany(x => x).Where(x => x.Contains("true"));

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM