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

时间:2011-08-15 21:31:51

标签: c# linq

我有一个类型字典:

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.

我如何得到我的期望。

3 个答案:

答案 0 :(得分:27)

这样的东西?

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

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

的项目

答案 1 :(得分:1)

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

答案 2 :(得分:1)

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