Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Tuesday, February 15, 2011 10:39 PM
I have two Dictionary collections (dictA and dictB) containing instances of an object, and I would like to find instances in dictA and not in dictB (and vice versa). Is there a straightforward way to accomplish this without manually writing two for loops?
Thanks in advance
All replies (3)
Wednesday, February 16, 2011 12:08 AM âś…Answered | 1 vote
Add, at the top of your C# file:
using System.Linq;
"Intersect" and "Except" are extension methods defined on the Enumerable class, and will work on any type that implements IEnumerable<T>, including Dictionary<T,U>.Keys.
Reed Copsey, Jr. - http://reedcopsey.com
If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
Tuesday, February 15, 2011 10:44 PM | 1 vote
To check against keys:
// var dictionaryA;
// var dictionaryB;
var intersection = dictionaryA.Keys.Intersect(dictionaryB.Keys);
var extraKeysInA = dictionaryA.Keys.Except(intersection);
var extraKeysInB = dictionaryB.Keys.Except(intersection);
Values could be done similarly.
Reed Copsey, Jr. - http://reedcopsey.com
If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
Tuesday, February 15, 2011 11:55 PM
There must be something I'm missing - when I look at the Keys property on my Dictionary<TKey, TValue> objects, the only methods I see are:
- CopyTo
- Count
- Equals
- GetEnumerator
- GetHashCode
- GetType
- ToString
There is no Intersect or Except method listed in intellisense. I'm using .NET 3.5 SP1