c# complex objects comparison

試著忘記壹切 提交于 2019-12-04 07:38:40

问题


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:


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.




回答2:


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"


来源:https://stackoverflow.com/questions/3526766/c-sharp-complex-objects-comparison

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!