Reputation: 249
I have a UI which gets populated from user selections. The key of my dictionary is just a simple string, but it may correspond to multiple string entries (the List).
If the user makes different selections, I should be able to go through this dictionary,and for the same string key, check whether a string from the selections that the user just made in my List already exists, and if it does, not add it. If it doesn't exist, then add to the already existing list.
I started with the following code:
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);
}
}
}
where listViewColumns
is a listview containing the entries that go into the dictionary keys, and m_ColumnAssociations
is my dictionary. I am adding entries elsewhere to my code, so this part is sorted. My questions is on the checking which is being done here.
In my current attempt I am trying only to get a value for now (correspondingMatrices
) but this statement returns me an IEnumerable. Any help would be appreciated.
Upvotes: 0
Views: 7263
Reputation: 2820
If I understand your problem right, you need something the following:
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);
}
}
}
}
}
or you can use Distinct
method:
...
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();
}
...
Hope it will help
Upvotes: 1