Creating a dictionary from another dictionary using LINQ

后端 未结 3 2087
自闭症患者
自闭症患者 2020-12-29 04:59

I have a dictionary of the type:

IDictionary> my_dictionary

bar class looks like this:

cl         


        
相关标签:
3条回答
  • 2020-12-29 05:33

    Something like this?

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

    That will only include items where at least one of the values IsValid.

    0 讨论(0)
  • 2020-12-29 05:37
    my_dictionary.Where(p => p.Any(v => v.Value.IsValid())
                 .ToDictionary(p=> p.Key,
                               p=> p.Value.Where(x => x.Value.IsValid());
    

    Get Only the Items that have a true in the Value, then only get the items that are true into the new dictonary.

    Filter then create the dictonary

    0 讨论(0)
  • 2020-12-29 05:45
    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());
    
    0 讨论(0)
提交回复
热议问题