tags:

views:

705

answers:

3

Hello,

I am trying to use LINQ to retrieve 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, both result in a compiler error.

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

How do I go about using LINQ to find values in a dictionary?

Thank you,

Rick

+11  A: 

Either

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

or

var q1 = testDict.Where(p => p.Value == "Apple");
veggerby
Just to clarify, the reason this works is that the dictionary acts as an IEnumerable<KeyValuePair<TKeyType, TValueType>>
Frank Schwieterman
Second expression should also have p.Value == "Apple" as p will be a Pair<,>.
Richard
Those will get you an expression that returns an IEnumerable result. If you actually want the actual object, you have to call Single() or First()
Nader Shirazie
Of course you are right Richard, edited...
veggerby
I used this answer to solve a problem. Thanks.
Phil
+3  A: 

you have an extra "from obj in" in your statements that isn't needed. Either remove that or change the .Where to the linq query syntax instead of the method syntax.

var q1 = from obj in testDict.Values
         where p == "Apple"
         select p;    
var q2 = testDict
         .Where(p => p.Value == "Apple")
         .Select(p => p.Value);
Scott Ivey
First expression should also have p.Value == "Apple" as p will be a Pair<,>.
Richard
Not true, he's selecting from testDict.Values, which is an IEnumerable<string>. He'd only get KeyValuePairs if he selected from testDict itself.
Joel Mueller
A: 

Wow! You guys are fast.

Thank you so much.

Rick

rboarman
Remember to mark the answer as accepted so the guys writing answers get their credit. :-)
Marpe
I don't see how to do that. :(
rboarman
I think you click on the little check item icon to the left of the answer you like to accept. (hover it and you'll see a tooltip)
Marpe
I found it! :) Thank you
rboarman
You're welcome. :)
Marpe