0

I've got something like this:

       var myDictionary = new Dictionary<string, string>()
            {
                {"x" ,"y" }
            }; 


        var listIWantToRetriveWithDictKeys = MyDbContext.Documents.ToList().Where(c => myDictionary.ContainsKey(c.SomethingLikeX)).Select(id => id.documentID).ToList();
        var listaIWantToRetriveWithDictValues = Documents.Where(o => myDictionary.ContainsValue(o.somethingLikeY.ToString())).Select(i => i.documentID).ToList();

I know about a method "contains" used with lists to have something like ...where(c => myList.Contains(c.Id).... but I want to achive something similar with dictionary. I don't normally use dictionaries, I know very little when it comes to them but the usage seems fitting here.

Currently the error says that the key is null and doesn't let me retrive any lists. Where is the problem here? Isn't the key "x"? Or the key should be an int?

Exact error:

System.ArgumentNullException: 'Value cannot be null.
Parameter name: key'

Error when removing ToList() after Documents:

System.NotSupportedException: 'LINQ to Entities does not recognize the method 'Boolean ContainsKey(System.String)' method, and this method cannot be translated into a store expression.'

Someone flagged this question as duplicate of "what does null referecence means". I know that somewhere there is a null in my query but for me, there is key there. Isn't it "x"?

Alice
  • 173
  • 1
  • 15
  • 1
    It would be awesome if you could provide a [mcve] (with sample inputs and expected results based on those sample inputs). Also, please update your question with the **exact** exception being thrown, and the exact bit of code that throws it. Also, remove the `ToList` after `Documents` - unless you are meaning to pull all documents over the wire. – mjwills Aug 27 '18 at 11:44
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – mjwills Aug 27 '18 at 11:48
  • Yes, but you already told that the problem is you don't know what is dictionary. And also simple debug session will show you where is null passed and we only can guess. – Renatas M. Aug 27 '18 at 11:59

1 Answers1

0

Try with checking c.SomethingLikeX != null before Contains.

var myDictionary = new Dictionary<string, string>()
    {
        {"x" ,"y" }
    }; 


var listIWantToRetriveWithDictKeys = MyDbContext.Documents.ToList().Where(c => c.SomethingLikeX != null && myDictionary.Keys.Contains(c.SomethingLikeX)).Select(id => id.documentID).ToList();
var listaIWantToRetriveWithDictValues = Documents.Where(o => c.somethingLikeY != null && myDictionary.Values.Contains(o.somethingLikeY.ToString())).Select(i => i.documentID).ToList();
Karan
  • 12,059
  • 3
  • 24
  • 40