M K Sharma
M K Sharma

Reputation: 163

How get unmatched list from dictionary

I want to get unmatched dictionary based on list item using LINQ. Please refer my sample code

Dictionary<string, List<int>> lowerActionRoles = new Dictionary<string, List<int>>();
Dictionary<string, List<int>> upperActionRoles = new Dictionary<string, List<int>>();

lowerActionRoles.Add("11", new List<int>() { 1, 2, 4 });
upperActionRoles.Add("11", new List<int>() { 1, 2, 4, 5 });
lowerActionRoles.Add("13", new List<int>() { 1, 2, 4 });

lowerActionRoles.Add("21", new List<int>() { 1, 2, 4 });
upperActionRoles.Add("21", new List<int>() { 1, 2, 4 });

Here I have 2 dictionary lowerActionRoles and upperActionRoles. Dictionary with key 21 matched and key 11 is not matched. Here I want get dictionary with key 11.

Upvotes: 0

Views: 228

Answers (2)

er-sho
er-sho

Reputation: 9771

You can test if there is key present in both of dictionaries by using ContainsKey and then for checking values of that list by using SequenceEqual like

var result = upperActionRoles
             .Where(entry => lowerActionRoles.ContainsKey(entry.Key) && !lowerActionRoles[entry.Key].SequenceEqual(entry.Value))
             .ToDictionary(entry => entry.Key, entry => entry.Value);

And to display your result on the console window,

foreach (var item in result)
{
    Console.WriteLine("Key: " + item.Key);
    Console.WriteLine();
    item.Value.ForEach(x => Console.WriteLine("Value: " + x));
}

Console.ReadLine();

Output:

enter image description here

Note: If you want to get a list from another dictionary then just switch the dictionaries name on above query.

Upvotes: 0

vc 74
vc 74

Reputation: 38179

Based on the assumption that items in only one of the dictionaries should be ignored:

lowerActionRoles.Where(entry =>
{
    if (upperActionRoles.TryGet(entry.Key, out List<int> upperActionList))
    {
        return !upperActionList.SequenceEqual(entry.Value);
    }
    else
    {
        return false;
    }
}

This will return you a collection of entries in lowerActionRoles (IEnumerable<KeyValuePair<string, List<int>>>).

If you're interested only in the keys, add

.Select(entry => entry.Key);

to the previous query

and to convert to a new dictionary:

.ToDictionary(entry => entry.Key, entry => entry.Value);

Upvotes: 1

Related Questions