Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Lambda with Dictionaries

Tags:

c#

lambda

linq

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

like image 337
rboarman Avatar asked Jul 01 '09 16:07

rboarman


People also ask

What is lambda in dictionary in Python?

A lambda is simply a way to define a function in Python. They are sometimes known as lambda operators or lambda functions. By now you probably have defined your functions using the def keyword, and it has worked well for you so far.

Can == operator be used on dictionaries?

According to the python doc, you can indeed use the == operator on dictionaries.


1 Answers

Either

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

or

var q1 = testDict.Where(p => p.Value == "Apple");
like image 78
veggerby Avatar answered Sep 28 '22 10:09

veggerby