简体   繁体   中英

difference between two dictionarys using linq

I'm have been playing around with linq this morning and have a questions about comparing two dictionarys. I want to compare two dicionarys and return the difference. I am able to produce my desired output by minuplating the query in my foreach loop. However, I'm wondering if there is an operator that would allow me to simplify this a bit more. Below I have listed the code i would like to simplify.

var _ItemsBefore = new SortedDictionary<int, int>() { { 1, 12 }, { 2, 12 } };
var _ItemsAfter  = new SortedDictionary<int, int>() { { 1, 11 }, { 2,  8 } { 3,  1 } };

foreach(var item in _ItemsAfter.Except(_ItemsBefore))
{
  if(_ItemBefore.ContainsKey(item.Key))
    Console.WriteLine(string.format("{0} {1}", item.Key, _ItemsAfter[item.Key] -_ItemsBefore[item.Key]));
  else
    Console.WriteLine(string.format("{0} {1}", item.Key, item.Value)
}

results
1 -1
2 -4
3  1

By your requirements, This is a linq version, but it's not as readable as your for loop version:

var result = _ItemsAfter
             .Except(_ItemsBefore)
             .Select(x => _ItemsBefore.ContainsKey(x.Key) ?
                     new KeyValuePair<int, int>(x.Key, x.Value - _ItemsBefore[x.Key]) :
                     new KeyValuePair<int, int>(x.Key, x.Value)).ToList();

You may want to be careful about how you store a lack of items, if you are deleting values when you have no inventory then you will not print out that reduction in inventory. However if you are storing 0, then you should not have a problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM