user3342876
user3342876

Reputation: 107

How to use lambda expression to select specific item?

I am just learning lambda expression and I want to use lambda expression to select any specific item. Here, I want to select a person with key = 1 so that selectedOne = "sanjay"

    var people = new Dictionary<int, string>();
    people.Add(1, "sanjay");
    people.Add(2, "roshan");
    people.Add(3, "neejesh");
    people.Add(4, "deep");   
    var selectedOne = people.Select(x => x.Key == 1);

How should I construct my lambda query?

Thanks!

Upvotes: 1

Views: 14703

Answers (4)

Ammar
Ammar

Reputation: 152

It looks like you are mixing the concept of Lambda Expression and LINQ. You have used the Lambda Expression. But if you have to use LINQ the first condition is the data collection you are using must implements IEnumerable interface e.g. LIST<T> Now write your LINQ code as:

var selectedOne = (from p in people
                  select p
                  where p.Key == "1").Single()

Upvotes: 0

Shane
Shane

Reputation: 459

You want to use a Where call to filter the result set to the person you want, then use Select to define the results you want, e.g.

var selectedOne = people.Where(x => x.Key == 1).Select(x => x.Value).First();

It would be much more efficient to perform the look up via the dictionaries index as suggested by pwas

Upvotes: 3

Gimly
Gimly

Reputation: 6175

The code should be something like:

var selectedOne = people.Single(x => x.Key == 1);

This will give you the keyvalue pair. If you want the string only:

var selectedOne = people.Single(x => x.Key == 1).Value;

Upvotes: 0

user2160375
user2160375

Reputation:

Dictionary is implements IEnumerable of KeyValuePair that contains Key and Value property:

var selectedOne = people.First(x => x.Key == 1).Value;

You are using wrong LINQ method. Select is used to project some values (transform one into another). You need to filter instead (search via specified key).

But... using LINQ to select dictionary key is not efficient. Better is:

var selectedOne = people[1];

It's amortized O(1) against O(n) - huge difference.

Upvotes: 8

Related Questions