簡體   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