检查字典<string,list <string =“”>&gt;中是否已存在值

时间:2016-05-06 12:56:01

标签: c# .net linq dictionary

我有一个从用户选择中填充的UI。我的字典的关键字只是一个简单的字符串,但它可能对应多个字符串条目(List)。

如果用户做出不同的选择,我应该能够浏览这个字典,并且对于相同的字符串键,检查用户刚刚在我的列表中做出的选择中的字符串是否已经存在,以及它确实,而不是添加。如果它不存在,则添加到现有列表中。

我从以下代码开始:

CommandLineComponent

其中commands是包含进入字典键的条目的列表视图,var checkedItems = listViewColumns.CheckedItems; if (checkedItems != null) { foreach (ListViewItem item in checkedItems) { if ((m_ColumnAssociations.ContainsKey(item.Text)) { var correspondingMatrices = m_ColumnAssociations.Where(kvp => kvp.Value.Contains(dgvMatrices.SelectedCells[0].Value.ToString())). Select(kvp => kvp.Key); } } } 是我的字典。我在其他地方添加条目到我的代码,所以这部分是排序的。我的问题是关于这里正在进行的检查。

在我目前的尝试中,我只想尝试获取一个值(listViewColumns)但是这个语句会返回一个IEnumerable。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

如果我理解你的问题,你需要以下内容:

var checkedItems = listViewColumns.CheckedItems;
if (checkedItems != null)
{
    foreach (ListViewItem item in checkedItems)
    {
        List<string> itemsForAdding = // some items that needs to be added

        // check if dictionary has the key
        if (m_ColumnAssociations.ContainsKey(item.Text)) 
        {
            var listFromDictionary = m_ColumnAssociations[item.Text];

            foreach(var itemForAdding in itemsForAdding)
            {
                if(!listFromDictionary.Contains(itemForAdding)
                {
                    listFromDictionary.Add(itemForAdding);
                }
            }
        }
    }
}

或者您可以使用Distinct方法:

...
List<string> itemsForAdding = // some items that needs to be added

// check if dictionary has the key
if (m_ColumnAssociations.ContainsKey(item.Text)) 
{
    var listFromDictionary = m_ColumnAssociations[item.Text];

    // add the whole list
    listFromDictionary.AddRange(itemsForAdding);

    // remove the duplicates from the list and save it back to dictionary
    m_ColumnAssociations[item.Text] = listFromDictionary.Distinct();
}
...

希望它会有所帮助

相关问题