Using lambda with dictionaries

I am trying to use LINQ to extract some data from a dictionary.

var testDict = new Dictionary<int, string>(); testDict.Add(1, "Apple"); testDict.Add(2, "Cherry"); var q1 = from obj in testDict.Values.Where(p => p == "Apple"); var q2 = from obj in testDict.Where(p => p.Value == "Apple"); 

The above lines, q1 and q2, lead to a compiler error.

 error CS0742: A query body must end with a select clause or a group clause 

How do I use LINQ to find values ​​in a dictionary?

Thanks,

Rick

+7
c # lambda linq
source share
2 answers

Or

 var q1 = from obj in testDict.Values where obj == "Apple" select obj; 

or

 var q1 = testDict.Where(p => p.Value == "Apple"); 
+24
source share

you have additional "from obj in" in your statements that are not needed. Either remove this, or change .Where to linq query syntax instead of method syntax.

 var q1 = from obj in testDict.Values where obj.Value == "Apple" select obj; var q2 = testDict .Where(p => p.Value == "Apple"); 
+8
source share

All Articles