我有一个字典,格式如下:
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.
如何获得我所期望的结果。
ToDictionary
之前使用Where
来过滤集合。 - Kirk BroadhurstIEnumerable<KeyValuePair<foo, IEnumerable<bar>>>
,所以情况比那更复杂一些。第一个 .Where() 是检查每个 KeyValuePair 中是否有任何一个bar
是有效的,但它实际上并没有过滤bar
本身只包括有效的。如果你有一个KeyValuePair
,其值包含有效和无效的混合,那么无效的仍然需要稍后被过滤掉。 - StriplingWarrior