开发者

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 b开发者_Python百科e 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?


To do it in a single statement:

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


Try using Enumerable.Select:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜