过滤字典字符串键,列出对象,其中对象包含属性值

时间:2018-05-31 09:40:03

标签: c# list linq dictionary

嗨,我有一个这个对象

public class Field 
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Dictionary<string, List<Field>> fields = new Dictionary<string, List<Field>>();

fields.Add(
     "pippo", 
     new List<Field>() { 
         new Field() { Name = "1" }, 
         new Field() { Name = "2" }, 
         new Field() { Name = "3" } 
});

fields.Add(
     "pluto", 
     new List<Field>() { 
         new Field() { Name = "1" }, 
});

fields.Add(
     "paperino", 
     new List<Field>() { 
         new Field() { Name = "3" } 
});

我想从字典中删除名称字段中字符串“1”的值中没有的所有键,如下例所示

fields: key "pippo" value { { Name = "1" }, { Name = "2" }, { Name = "3" } }
        key "pluto" value { { Name = "1" }}

3 个答案:

答案 0 :(得分:0)

如果您想修改现有字典,为什么不找出密钥然后将其删除?

var keysToRemove = fields
  .Where(pair => !pair.Value.Any(item => item.Name == "1"))
  .Select(pair => pair.Key);

foreach (var key in keysToRemove)
  fields.Remove(key);

答案 1 :(得分:0)

一种方法是使用linq:

var result = fields
    .Where(f => f.Value.Any(x => x.Name == "1"))
    .ToDictionary(k => k.Key, v => v.Value);

请注意,这不会更改原始字典,但会返回新的字典。如果您想更改原始字典,只需使用它而不是var result - fields = fields.Where....

答案 2 :(得分:0)

使用Where后跟ToDictionary

fields = fields.Where(x => x.Value.Any(y => y.Name == "1"))
               .ToDictionary(x => x.Key, x => x.Value);