使用LINQ从另一个字典创建字典

我有一个类型的字典:

IDictionary<foo, IEnumerable> 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 { new bar {IsValid = false}, new bar {IsValid = false}, new bar {IsValid = false}}; my_dictionary[foo2] = new List {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. 

我如何得到我的期望。

像这样的东西?

 my_dictionary .Where(p=> p.Value.Any(x => x.IsValid)) .ToDictionary( p=> p.Key, p=> p.Value.Where (x => x.IsValid)); 

这将只包含至少有一个值IsValid

 my_dictionary.Where(p => p.Any(v => v.Value.IsValid()) .ToDictionary(p=> p.Key, p=> p.Value.Where(x => x.Value.IsValid()); 

仅获取值中具有true的项目,然后仅获取新的dictonary中的项目。

过滤然后创建dictonary

 var new_dict = my_dictionary.Select(x => new KeyValuePair>( x.Key, x.Value .Where(y => y.IsValid) .ToList())) .Where(x => x.Value.Count > 0) .ToDictionary(x => x.Key, x => x.Value.AsReadOnly());