簡體   English   中英

C#列表 <Dictionary<string,string> &gt;添加獨特的字典

[英]c# List<Dictionary<string,string>> add unique dictionaries

我有一個字典清單:

List<Dictionary<string, string>> items = new List<Dictionary<string, string>>();

foreach (var group in groupedItems)
{

    foreach (var item in group)
    {
         Dictionary<string, string> newItem = new Dictionary<string, string>();
         newItem.Add("name", item.Name);
         newItem.Add("value", item.Value);
    }
 }

items.Add(newItem);

基本上,當我循環瀏覽分組的項目時,我會創建一個Dictionary,其中的鍵是item.Name,值是item.Value。 在分組的情況下,這將導致列表中詞典的重復。

如何避免將重復的詞典添加到此列表?

我有一個foreach循環,我想一次添加一些項目。

首先想到的是創建您自己的extends Dictionary<string, string>的類,並實現您自己的GetHashCode()Equals

public class MyDictionary : Dictionary<string, string>
{
    public override int GetHashCode() 
    {
        ...
    }

    public override bool Equals(object source) 
    {
        ...
    }
}

Equals您實現了平等機制,在GetHashCode您實現了一種機制,該機制根據您的平等標准為兩個相同的字典產生相同的數值。

然后,使用HashSet<MyDictionary>代替List<Dictionary<string, string>> 由於集合不允許重復,因此您應該以唯一的字典集合作為結尾。

我以這種方式解決了這個問題:

我創建了一個新字典:

Dictionary<string, string> control = new Dictionary<string, string>();

然后我就這樣:

Dictionary<string, string> newItem = new Dictionary<string, string>();
newItem.Add("name", item.Name);
newItem.Add("value", item.Value);

if (!control.ContainsKey(item.Name))
{
   control.Add(item.Name);
   items.Add(newItem);
}

您可以實現自己的EqualityComparer來確定兩個字典是否相等:

class EqualityComparer<Dictionary<string, string>> : IEqualityComparer<Dictionary<string, string>>
{

    public bool Equals(Dictionary<string, string> x, Dictionary<string, string> y)
    {
        // your code here
    }

    public int GetHashCode(Dictionary<string, string> obj)
    {
        // your code here
    }
}

現在,您可以在檢查新項目是否存在時使用此比較器:

foreach (var g in groupedItems)
{
    Dictionary<string, string> newItem = new Dictionary<string, string>();

    foreach(var item in g) 
    {
        newItem.Add("name", item.Name);
        newItem.Add("value", item.Value);    
    }
    if (!items.Contains(newItem, new EqualityComparer()) items.Add(newItem);
}

因此,無需創建Dictionary的新實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM