views:

77

answers:

2

Hi Everyone,

 public class SecurityMaster : EntityObject
 {
    public string BondIdentifier { get; set; }
    public string Description { get; set; }
     public EntityCollection<SecurityMasterSchedules> SecurityMasterSchedules { get; set}
  }
 public class SecurityMasterSchedules :EntityObject
 {
       public string BondIdentifier { get; set; }
       public decimal rate { get; set; }
       public datetime startdate { get; set; }
       public datetime endate { get; set; }
 }

How do I compare the objects List list1 and List list2? IEnumerable except method doesn't work with complex objects.

   List<SecurityMaster> list1 = new List<SecurityMaster>();
   List<SecurityMaster> list2 = new List<SecurityMaster>();
+1  A: 

I'm not sure what your code has to do with anything, but here's how you use Except:

var list1 = new int[] { 1, 2, 3 };
var list2 = new int[] { 1 };

var output = list1.Except(list2).First();

Console.WriteLine(output);  // prints "2"
ladenedge
+2  A: 

I'm guessing you have two IEnumerable<EntityObject> sequences and you want to know how to use Except in a way that treats two EntityObjects as identical under specific criteria. I'm going to further guess that these criteria comprise one simple rule (just to make life easier for myself in providing this answer): two items with the same BondIdentifier property will be considered identical.

Well, then, use the overload for Except that accepts an IEqualityComparer<T>:

class EntityObjectComparer : IEqualityComparer<EntityObject>
{
    public bool Equals(EntityObject x, EntityObject y)
    {
        string xId = GetBondIdentifier(x);
        string yId = GetBondIdentifier(y);

        return x.Equals(y);
    }

    private string GetBondIdentifier(EntityObject obj)
    {
        var sm = obj as SecurityMaster;
        if (sm != null)
        {
            return sm.BondIdentifier;
        }

        var sms = obj as SecurityMasterSchedules;
        if (sms != null)
        {
            return sms.BondIdentifier;
        }

        return string.Empty;
    }
}

List<EntityObject> list1 = GetList1();
List<EntityObject> list2 = GetList2();

var itemsInList1NotInList2 = list1.Except(list2, new EntityObjectComparer());

Even if my guess as to the criteria was wrong, you can still use this answer as a basis from which to formulate your own.

If my initial guess was also wrong, then clearly this answer is useless to you.

Dan Tao