Jamie Treworgy
Jamie Treworgy

Reputation: 24344

Get keys as List<> from Dictionary for certain values

While similar to this question which gave me the LINQ for part of my problem, I'm missing something that seems like it must be obvious to avoid the last step of looping through the dictionary.

I have a Dictionary and I want to get a List of keys for just the items for which the value is true. Right now I'm doing this:

Dictionary<long,bool> ItemChecklist;
...


var selectedValues = ItemChecklist.Where(item => item.Value).ToList();

List<long> values = new List<long>();
foreach (KeyValuePair<long,bool> kvp in selectedValues) {
   values.Add(kvp.Key);
}

Is there any way I can go directly to a List<long> without doing that loop?

Upvotes: 4

Views: 6539

Answers (2)

MarkXA
MarkXA

Reputation: 4384

To do it in a single statement:

var values = ItemChecklist.Where(item => item.Value).Select(item => item.Key).ToList();

Upvotes: 6

Mark Byers
Mark Byers

Reputation: 839124

Try using Enumerable.Select:

List<long> result = ItemChecklist.Where(kvp => kvp.Value)
                                 .Select(kvp => kvp.Key)
                                 .ToList();

Upvotes: 4

Related Questions