C#复杂对象比较 [英] c# complex objects comparison

查看:206
本文介绍了C#复杂对象比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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; }
     }

如何比较对象列表list1和列表list2? IEnumerable除外,方法不适用于复杂对象.

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>();

推荐答案

我猜您有两个IEnumerable<EntityObject>序列,并且您想知道如何以将两个EntityObjects视为相同的方式使用Except根据特定标准.我将进一步猜测,这些条件仅包含一个简单的规则(只是为了让我自己更轻松地提供此答案):具有相同BondIdentifier属性的两个项目将被视为相同.

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.

然后,对接受IEqualityComparer<T>Except使用重载:

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.

这篇关于C#复杂对象比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆