16

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();
Community
  • 1
  • 1
mituw16
  • 5,126
  • 3
  • 23
  • 48

3 Answers3

33

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);
D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • 1
    This is exactly what I was trying to achieve, and it works flawlessly in my application. Thank you! – mituw16 Feb 11 '14 at 14:30
  • I tried for hours to get something like that working with the `Select()` method. All I needed was the `ToDictionary()`. Thanks mate! – Sebastian Jan 20 '16 at 08:16
  • This post helps me to understand how to use `.ToDictionary()` in Linq. Thanks buddy sample code where i used `ToDictionary()` method `ctx.SalesSummaries.ToDictionary(x => x.TableNumber, x => x.Status)` – Niraj Trivedi Aug 09 '17 at 01:37
5

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.

Michael Eakins
  • 4,149
  • 3
  • 35
  • 54
Christos
  • 53,228
  • 8
  • 76
  • 108
1

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.

Rene Hilgers
  • 390
  • 3
  • 13
  • This doesn't result in a dictionary, it results in an `IEnumerable>` - the same as an `IEnumerable`, but with the extra overhead of the Key as well. – Zac Faragher Aug 21 '17 at 04:21