简体   繁体   English

使用linq的两个dictionarys之间的差异

[英]difference between two dictionarys using linq

I'm have been playing around with linq this morning and have a questions about comparing two dictionarys. 今天早上我一直在玩linq并且有关于比较两个词典的问题。 I want to compare two dicionarys and return the difference. 我想比较两个dicionarys并返回差异。 I am able to produce my desired output by minuplating the query in my foreach loop. 我可以通过在foreach循环中最小化查询来生成我想要的输出。 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: 根据您的要求,这是一个linq版本,但它不像您的for循环版本那样可读:

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. 但是,如果您存储0,那么您应该没有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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