【发布时间】:2011-08-16 06:04:12
【问题描述】:
我有一本这样的字典:
IDictionary<foo, IEnumerable<bar>> my_dictionary
bar 类如下所示:
class bar
{
public bool IsValid {get; set;}
}
如何创建另一个字典,其中仅包含 IsValid = true 的那些项目。
我试过了:
my_dictionary.ToDictionary( p=> p.Key,
p=> p.Value.Where (x => x.IsValid));
上述代码的问题在于,如果该键的所有元素都是 IsValid = false,则这会创建一个可枚举为空的键。
例如:
my_dictionar[foo1] = new List<bar> { new bar {IsValid = false}, new bar {IsValid = false}, new bar {IsValid = false}};
my_dictionary[foo2] = new List<bar> {new bar {IsValid = true} , new bar{IsValid = false};
var new_dict = my_dictionary.ToDictionary( p=> p.Key,
p=> p.Value.Where (x => x.IsValid));
// Expected new_dict should contain only foo2 with a list of 1 bar item.
// actual is a new_dict with foo1 with 0 items, and foo2 with 1 item.
我如何得到我的期望。
【问题讨论】: