Linq: except for two different types of dictionaries

I have 2 different types of dictionaries Dictionary<int, Fooclass> oldDic and Dictionary<int, string> barList newDic . Now I need to compare the values ​​in both dictionaries. for example, maybe

  • oldDic: 1,2,3
  • newDic: 1,2,3,4
  • Expected Result: 4

Now I need to compare both dictionaries based on their keys; any help would be appreciated.

Edit: The output should look like the second dictionary (newDic), but this will contain some value from the second dictionary (oldDic). for instance

1, "fooString" Where fooString is some value in Fooclass someproperty .... For clarity see this, that did not work for me

 var addedList = from list1 in baseListDic join list2 in trackerlist on list1.Key equals list2.Key select new { key = list1.Key, value = list1.Value._lead }; 

here baseListDic is oldDic and trackerlist is newDic .... Let me know if I haven't figured it out yet ...

+6
source share
4 answers

It would be easier to just create a new dictionary based on the new dictionary, ignoring elements that have the same key in the old dictionary.

 var result = newDic .Where(kvp => !oldDic.ContainsKey(kvp.Key)) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); 
+9
source

Note. Despite your question: β€œI need to compare values in both dictionaries” (my underscore), your example seems to demonstrate just a comparison of keys, so I went with that. If these are the values ​​you need to compare, you can give an example of what you mean and if they are easily convertible or comparable ...

If you are actually comparing keys, you can simply use the .Keys property of the dictionary, which returns an IEnumerable<TKey> , which you can use in your linq ...

eg:

 var expectedOutput = newDic.Keys.Except(oldDic.Keys); 

It relies on a key of the same type, but it goes without saying if you are comparing. Of course, there is nothing that would prevent you from first converting their types if you do this with different types.

Also, if you want to get values ​​in one of the dictionaries, you can do something like:

 var newDicValues = expectedoutput.Select(x=>newDic[x]); 

Or, you know, do any other things you like. :)

+5
source

Try this to get the difference between two different lists: if they have a common property.

  var differentItems = List<Type1>.Select(d => d.Name) .Except(List<Type2>.Select(d => d.Name)); 
+2
source

If you understood correctly, try something like this.

if you have a separate dictionary similar to this Dictionary<int, Fooclass> FinalDict

  IEnumerable<int> list = OldDic.Keys.Except(NewDic.Keys); foreach (var x in list) { var value =new MyClass(); OldDic.TryGetValue(x,out value ); FinalDict.Add(x,value); } 

So, in the dictionary called FinalDict, the key and associated Fooclass will appear

Hope this helps

0
source

Source: https://habr.com/ru/post/921319/


All Articles