2

I've a Dictionary<MyEntity1, IList<MyEntity2>> and I have an object of MyEntity2 which I know it is in one (and only one) of the lists of the dictionary (I've even seen it while debugging). How ever the following query is returning null:

IDictionary<MyEntity1, IList<MyEntity2>> myDictionary = new Dictionoary<MyEntity1, IList<MyEntity2>>();
MyEntity1 myEntity1 = (from p in myDictionary
                       where p.Value.Contains(myEntity2)
                       select p.Key) as MyEntity1;

What am I doing wrong?

3
  • Please edit your post so the full definition of Dictionary<MyEntity1, IList<MyEntity2>> is visible Commented Jun 22, 2011 at 17:31
  • Ok, I'll edit it, but the answer posted a few seconds ago worked (I didn't get to see who posted it). Commented Jun 22, 2011 at 17:32
  • @Richard Morgan: no, I'm not. Commented Jun 22, 2011 at 17:34

3 Answers 3

6
var myEntity1 = (from p in myDictionary
                where p.Value.Contains(myEntity2)
                select p.Key).First();

LINQ queries always return collections, even if with only one object instance

Sign up to request clarification or add additional context in comments.

2 Comments

Will this return null if no object found?
@Diego: no, it will not return null... it will throw an exception if not found. use.FirstOrDefault() if you want a null instead.
1

You should use something like

   MyEntity1 myEntity1 = (from p in myDictionary
                   where p.Value.Contains(myEntity2)
                   select p.Key).FirstOrDefault();

The query will return an IEnumerable<MyEntity1> and casting that to MyEntity1 will always return null. The cast is invalid and as will return null.

Comments

1

Your problem is that the Select query returns an IEnumerable - which you can't cast to MyEntity1.

Try adding FirstOrDefault() - then you won't need the cast.

IDictionary<MyEntity1, IList<MyEntity2>> myDictionary = new Dictionary<MyEntity1, IList<MyEntity2>>();
var myEntity1 = (from p in myDictionary
                   where p.Value.Contains(myEntity2)
                   select p.Key).FirstOrDefault();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.