我有一个类型的字典:
IDictionary<foo, IEnumerable<bar>> my_dictionary
Run Code Online (Sandbox Code Playgroud)
bar类看起来像这样:
class bar
{
public bool IsValid {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
如何创建另一个只包含IsValid = true的项目的字典.
我试过这个:
my_dictionary.ToDictionary( p=> p.Key,
p=> p.Value.Where (x => x.IsValid));
Run Code Online (Sandbox Code Playgroud)
上面代码的问题是,如果该键的所有元素都是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.
Run Code Online (Sandbox Code Playgroud)
我如何得到我的期望.
Str*_*ior 32
像这样的东西?
my_dictionary
.Where(p=> p.Value.Any(x => x.IsValid))
.ToDictionary( p=> p.Key,
p=> p.Value.Where (x => x.IsValid));
Run Code Online (Sandbox Code Playgroud)
这将只包括至少有一个值的项目IsValid
.
归档时间: |
|
查看次数: |
14525 次 |
最近记录: |