Get keys as a list <> from a dictionary for specific values

While it looks like this question that LINQ gave me for part of my problem, I am missing something similar, which should be obvious in order to avoid the last step of the loop through the dictionary.

I have a dictionary, and I want to get a list of keys only for elements for which the value is true. Now I am 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 a way I can go directly to List<long> without doing this loop?

+4
source share
2 answers

To do this in one expression:

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

Try using Enumerable.Select :

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

Source: https://habr.com/ru/post/1332627/


All Articles