首页 > 解决方案 > 遍历 C# 中的字典值列表以检查特定键

问题描述

我想遍历字典值,它是 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
    {
    }
}

标签: c#dictionary

解决方案


这有点奇怪,但让我们尝试解决它。我们通常不想迭代字典的键。使用 one 的原因是,如果我们已经知道密钥,我们希望非常快速地获取值。

本着回答问题的精神,要遍历 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);
            }
        }
    }
}

推荐阅读