繁体   English   中英

从列表中查找和删除元素 <Dictionary<string, object> &gt;

[英]Find and remove elements from List<Dictionary<string, object>>

我目前正在使用C#4.7.2应用程序。 我要为自定义类型编写扩展方法,但不幸的是,我在LINQ查询中苦苦挣扎。

我需要过滤List<Dictionary<string, object>>以使用特定键在列表中查找Dictionary<string, object>的元素并将其从我的列表中删除。 此外,列表条目可以为空。

列表条目(字典)可能看起来像这样,可能有多个带有值键A的元素,我实际上需要删除所有元素:

Key    |  Value
"MyId" : "A",
"Width" : 100,
"Length" : 50

结构非常简单。 棘手的事情是在列表中找到字典元素。 我的扩展方法如下所示:

public static List<Dictionary<string, object>> RemoveItem(this List<Dictionary<string, object> items, string value)
{
    var itemToRemove = items.FirstOrDefault(x => x.ContainsKey("MyId")).Values.Contains(value);

    items.Remove(itemToRemove);

    return items;
}

不幸的是,此LINQ查询无法正常工作。

你知道如何解决这个问题吗?

非常感谢你!!

您要删除所有带有键和值的内容吗? 您甚至不需要LINQ:

public static int RemoveItems(this List<Dictionary<string, object>> dictionaryList, string value)
{
    int removed = dictionaryList
        .RemoveAll(dict => dict.TryGetValue("MyId", out object val) && value.Equals(val));
    return removed;
}

您可以使用列表的RemoveAll方法。 然后,您提供一个检查字典的谓词(这是KeyValuePair<TKey, TValue>的集合):

items.RemoveAll(dict => dict.Any(kv => kv.Key == "MyId" && ( kv.Value as string ) == "A"));

或如Tim Schmelter所建议:

items.RemoveAll(dict => dict.TryGetValue("MyId", out object value) && (value as string) == "A");

您将需要执行以下操作:

itemsToRemove = items.Where(x => x.ContainsKey("MyId") && x["MyId"].ToString() == value);

从您的描述中,您似乎想要第一个包含键的字典,该键具有参数value 那将是items.FirstOrDefault(x => x.ContainsKey(value))

您正在做的是获取包含一个预定义键"myId"的字典,然后遍历字典中的对象并将其值与value参数进行比较,这不是您想要的描述。

如果希望更多词典包含给定键,并且要删除所有list.RemoveAll(dict => dict.ContainsKey(value)) ,则应使用list.RemoveAll(dict => dict.ContainsKey(value))

public static List<Dictionary<string, object>> RemoveItem(this List<Dictionary<string, object>> items, string value, string key)
{
    foreach (var item in items)
    {
        if(item.ContainsKey(key) && item[key] == value)
        {
            item.Remove(key);
        }
    }

    return items;
}

这样就可以了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM