开发者

C# Linq query not working

开发者 https://www.devze.com 2023-03-14 14:13 出处:网络
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 debuggin

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 MyEnti开发者_开发技巧ty1;

What am I doing wrong?


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


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.


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号