简体   繁体   English

在字典中查找带有C#值列表的项目

[英]finding item in Dictionary with list of values in C#

I have the following class: 我有以下课程:

public class TransactionData

{

    private Dictionary<string, List<string>> transactionsAndFilesDictionary = new Dictionary<string, List<string>>();

    public bool FileBlocked(string transactionID, string fileName)
    {
        foreach (var entry in this.transactionsAndFilesDictionary)
        {
            if(entry.Value.Contains(fileName)){
                if(entry.Key==transactionID) return false;
                return true;
            }
        }
        return false;
    }
}

I have problem with FileBlocked method. 我有FileBlocked方法的问题。 Line if(entry.Value.Contains(fileName)) rises exception and I don't know why. if(entry.Value.Contains(fileName))异常,我不知道为什么。 I just simply want to check if the fileName exists for any transactionID . 我只是想检查fileName存在任何transactionID

Try code below. 请尝试以下代码。 You dictionary values is a list which I think is the issue 您的字典值是我认为是问题的列表

   public class TransactionData
    {

        private Dictionary<string, List<string>> transactionsAndFilesDictionary = new Dictionary<string, List<string>>();

        public bool FileBlocked(string transactionID, string fileName)
        {
            foreach (var key in this.transactionsAndFilesDictionary.Keys)
            {
                if (transactionsAndFilesDictionary[key].Where(x => x.Contains(fileName)).Count() > 0)
                {
                    return true;
                }
            }
            return false;
        }
    }​

I'm guessing - because you didn't show how you add entries to your dictionary - the list is not initialized at the time you invoke the FileBlocked method. 我猜-因为您没有显示如何向字典中添加条目-调用FileBlocked方法时未初始化列表。 If that's intentional, that is it's actually in accordance with your business logic to access a dictionary that may be empty than you first have to check if the Value exists. 如果这是故意的,那实际上是根据您的业务逻辑来访问可能为空的字典,这比您首先必须检查Value存在是必要的。 entry.Value != null should do the trick: entry.Value != null应该可以解决问题:

foreach (var entry in this.transactionsAndFilesDictionary)
{
    if (entry.Value != null &&
        entry.Value.Contains(fileName)){
        if(entry.Key==transactionID) return false;
        return true;
    }
}

If however accessing the entry.Value is an unexpected side effect and should never happen then you may be missing a List initialization when you add items to the dictionary. 但是,如果访问entry.Value是意外的副作用,并且永远不会发生,那么在将项目添加到字典时,可能会缺少List初始化。

Make sure that when adding a new myKey to the dictionary you initialize the list as well. 确保在向字典添加新的myKey也要初始化列表。 it's not initialized when you initialize the dictionary: 初始化字典时未初始化:

this.transactionsAndFilesDictionary[myKey] = new List<string>();

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

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