繁体   English   中英

遍历C#中的字典值列表以检查特定键

[英]Iterate over dictionary values list in C# to check for specific key

我想遍历字典值,它是C#中的字符串列表,以检查所有键

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

我想检查csvList中的每个键(字符串),并检查它是否存在于任何值(列表)中

foreach(var events in csvList)
{
   foreach(var action in csvList.Values) // But I want to loop through all the lists in dictionary, not just the list of event key
    {
    }
}

这有点奇怪,但让我们尝试解决它。 我们通常不希望迭代字典的键。 使用其中一个的原因是,如果我们已经知道密钥,我们希望很快获得值。

本着回答问题的精神,要遍历Dictionary的键,您必须使用Keys属性。 请注意,不能保证有关此集合的顺序。

var d = new Dictionary<string, int>();
d.Add("one", 1);
d.Add("two", 2);

foreach (var k in d.Keys) {
    Console.WriteLine(k);
}

但是我认为您可能有问题,选择了词典作为解决方案,然后在无法解决问题时来到这里。 如果字典不是问题怎么办?

听起来您有几个List<string>实例,并且您对特定列表是否包含特定字符串感兴趣。 也许您想知道,“哪个列表包含哪个字符串?” 我们可以用略有不同的字典来回答这个问题。 我将使用数组而不是列表,因为它更容易键入。

using System;
using System.Collections.Generic;

public class Program
{
    private static void AddWord(Dictionary<string, List<int>> d, string word, int index) {
        if (!d.ContainsKey(word)) {
            d.Add(word, new List<int>());   
        }

        d[word].Add(index);
    }

    private static List<int> GetIndexesForWord(Dictionary<string, List<int>> d, string word) {
        if (!d.ContainsKey(word)) {
            return new List<int>();
        } else {
            return d[word];
        }
    }

    public static void Main()
    {
        var stringsToFind = new[] { "one", "five", "seven" };

        var listsToTest = new[] {
            new[] { "two", "three", "four", "five" },
            new[] { "one", "two", "seven" },
            new[] { "one", "five", "seven" }
        };

        // Build a lookup that knows which words appear in which lists, even
        // if we don't care about those words.
        var keyToIndexes = new Dictionary<string, List<int>>();
        for (var listIndex = 0; listIndex < listsToTest.GetLength(0); listIndex++) {
            var listToTest = listsToTest[listIndex];
            foreach (var word in listToTest) {
                AddWord(keyToIndexes, word, listIndex);
            }
        }

        // Report which lists have the target words.
        foreach (var target in stringsToFind) {
            Console.WriteLine("Lists with '{0}':", target);
            var indices = GetIndexesForWord(keyToIndexes, target);
            if (indices.Count == 0) {
                Console.WriteLine("  <none>");
            } else {
                var message = string.Join(", ", indices);
                Console.WriteLine("  {0}", message);
            }
        }
    }
}
foreach(var events in csvList)
{
   foreach(var action in csvList.Values) 
    {
       if (action.Contains(events.Key)) //Just use this, there is no point to iterate the list as you can use contains method
    }
}

暂无
暂无

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

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