简体   繁体   中英

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. Line if(entry.Value.Contains(fileName)) rises exception and I don't know why. I just simply want to check if the fileName exists for any 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. 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. entry.Value != null should do the trick:

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.

Make sure that when adding a new myKey to the dictionary you initialize the list as well. it's not initialized when you initialize the dictionary:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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