Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get keys as List<> from Dictionary for certain values

Tags:

c#

linq

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?

like image 872
Jamie Treworgy Avatar asked Dec 28 '22 03:12

Jamie Treworgy


2 Answers

To do it in a single statement:

var values = ItemChecklist.Where(item => item.Value).Select(item => item.Key).ToList();
like image 53
MarkXA Avatar answered Feb 06 '23 22:02

MarkXA


Try using Enumerable.Select:

List<long> result = ItemChecklist.Where(kvp => kvp.Value)
                                 .Select(kvp => kvp.Key)
                                 .ToList();
like image 38
Mark Byers Avatar answered Feb 07 '23 00:02

Mark Byers