Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Except of multiple nested dictionaries using LINQ expression

I want to get different of n numbers of dictionaries using a lambda expression:

Dictionary<string, string> d1 = new Dictionary<string, string>();
d1.Add("Joe", "2, Barfield Way");
d1.Add("Mike", "17, Apollo Avenue");
d1.Add("Jane", "69, Lance Drive");


Dictionary<string, string> d2 = new Dictionary<string, string>();
d2.Add("Joe", "2, Barfield Way");
d2.Add("Jane", "69, Lance Drive");
// var diff = d1.Except(d2);

Let say I want to get the difference of two above dictionaries var diff = d1.Except(d2);

Now I want to get the same out using lambda expression for N numbers of dictionaries.

For an instant, I have merged two dictionaries into one. I want to get a difference of two dictionaries using lambda expression or any other LINQ expression.

Dictionary<string, Dictionary<string, string>> d = new Dictionary<string, Dictionary<string, string>>();
d.Add("Test", d1);
d.Add("Test2", d2);

I have tried the expression below but could not get any results.

d.Select(c => c.Value.Except(c.Value))
like image 821
Muhammad imran Avatar asked Jan 10 '20 07:01

Muhammad imran


2 Answers

You need some Linq methods:

var result = d.SelectMany(d => d.Value).GroupBy(c => c.Key)
              .Where(c => c.Count() == 1).ToDictionary(t => t.Key, t => t.Select(c => c.Value)
              .FirstOrDefault()).ToList();
like image 198
Salah Akbari Avatar answered Nov 20 '22 14:11

Salah Akbari


Convert it to a collection of KeyValuePair<> enumerables and follow the same logic using .Aggregate()

var result = d.Select(x => x.Value.AsEnumerable()).Aggregate((x, y) => x.Except(y));
like image 1
Innat3 Avatar answered Nov 20 '22 13:11

Innat3