Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Query Dictionary where value in List

Tags:

c#

linq

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();
like image 308
mituw16 Avatar asked Feb 11 '14 14:02

mituw16


3 Answers

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);
like image 156
D Stanley Avatar answered Nov 03 '22 19:11

D Stanley


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.

like image 5
Christos Avatar answered Nov 03 '22 18:11

Christos


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.

like image 1
Rene Hilgers Avatar answered Nov 03 '22 17:11

Rene Hilgers