0

i generate a list of an Object called Exceptions :

public class Exceptions
{
    public bool deleted { get; set; }
    public DateTime OriginalDate { get; set; }
    public DateTime StartUtc { get; set; }
    public DateTime EndUtc { get; set; }
    public Int32 NumParticipants { get; set; }
    public String Subject { get; set; }
    public String Location { get; set; }
}

List A got 2 Objects and List B got 3 Objects

I Expect a new List which shows me the difference between the two objects

i tried it with the following function:

var ListC = ListA.Except(ListB).ToList();

i get two objects in ListC which looks exactly like ListA.But i Expected the missing Object from List B.

what am I doing wrong?

Eray Geveci
  • 1,099
  • 4
  • 17
  • 39
  • Have you provided a custom implementation of `Equals` for your `Exceptions` class? If not, it will do reference comparisons. – adv12 May 28 '14 at 14:57
  • The missing `Equals`/`GetHashCode` methods aside, if you expect the "missing" object from list B, it should be `ListB.Except(ListA)`, not otherwise. – sloth May 28 '14 at 14:59
  • possible duplicate of [Difference between two lists](http://stackoverflow.com/questions/5636438/difference-between-two-lists) – qqbenq May 28 '14 at 15:00
  • @sloth i get 3 objects when i do it the other way – Eray Geveci May 28 '14 at 15:04
  • 1
    @ErayGeveci Unsurprisingly. You still have to implement `Equals`/`GetHashCode` or an `IEqualityComparer`. – sloth May 28 '14 at 15:10

4 Answers4

0

Expect uses a default equality comparer to compare your objects which compares them by reference.you need to implement a custom equality comparer and use that comparer with Except method.

You can find example on MSDN if you don't know how to implement IEqualityComparer<T> for your type.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • how can i do it when i have two lists? in your example it compares two single objects. could you give me an example please – Eray Geveci May 28 '14 at 16:22
0

You need to do like this:

var ListC = ListA.Except(ListB).Union(ListB.Except(ListA))
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
0

I would recommend you override the Equals() and GetHashCode() so that the comparison is as you'd expect.

public class Exceptions
{
   public override bool Equals(object o)
   {
      return this.Equals(o as Exceptions);
   }

   public bool Equals(Exceptions ex)
   {
       if(ex == null)
          return false;
       else
       {
           // Do comparison here
       }
   }
}
Dominic Zukiewicz
  • 8,258
  • 8
  • 43
  • 61
0

A Linq alternative, there could be a much faster approach: HashSet.SymmetricExceptWith():

var exceptions = new HashSet(listA);

exceptions.SymmetricExceptWith(listB);
dekajoo
  • 2,024
  • 1
  • 25
  • 36