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

如何比较对象 List list1 和 List list2?IEnumerable except 方法不适用于复杂对象。

   List<SecurityMaster> list1 = new List<SecurityMaster>();
   List<SecurityMaster> list2 = new List<SecurityMaster>();
4

2 回答 2

2

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.

于 2010-08-19T22:50:35.127 回答
1

我不确定您的代码与任何事情有什么关系,但这是您使用的方式except

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

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

Console.WriteLine(output);  // prints "2"
于 2010-08-19T22:28:53.337 回答