mituw16
mituw16

Reputation: 5250

Linq Query Dictionary where value in List

I have a Dictionary<string, string> and another List<string>. What I am trying to achieve is a linq query to get all items out of the dictionary where any values from said dictionary are in the List<string>.

I found this post to be helpful, LINQ querying a Dictionary against a List . And was able to write the following linq expression, however my results never actually return anything.

What I have so far.

Data is the dictionary and PersonList is the list of strings.

var Persons = PersonList.Where(x => Data.ContainsKey(x))
                        .Select(z => new { key = z, value = Data[z] })
                        .ToList();

Upvotes: 17

Views: 80238

Answers (3)

Christos
Christos

Reputation: 53958

Try this one:

var Persons = Data.Where(x=>PersonList.Contains(x.Value))
                  .Select(x=>new { key=x.Key, value=x.Value})
                  .ToList();

I converted the result to a list, because I noticed that you used it in your code. If you want it to a dictionary, just take a look to the answer provided by D Stanley.

Upvotes: 5

Rene Hilgers
Rene Hilgers

Reputation: 420

I think you don't have to convert it ToDictionary, because your source is a dictionary:

var Persons = Data.Where(kvp => personList.Contains(kvp.Key))
            .Select(x => x);

I quickly tested it in LinqPad, but if this is a bad idea or I'm wrong, please leave a comment.

Upvotes: 1

D Stanley
D Stanley

Reputation: 152511

Are you looking for keys or values? If you're looking for values use

var Persons = Data.Where(kvp => PersonList.Contains(kvp.Value))
                  .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

If instead you really want keys then your code should work but another option would be:

var Persons = Data.Where(kvp => PersonList.Contains(kvp.Key))
                  .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

Upvotes: 34

Related Questions