Generic Equals override for CSLA objects (LINQ to Objects help)

Generic Equals override for CSLA objects (LINQ to Objects help)

Old forum URL: forums.lhotka.net/forums/t/8064.aspx


Jack posted on Monday, November 30, 2009

I've found I keep writing custom linq statements to compare objects in a CSLA collection without using the object.Equals function and for some I can't determine how to write the linq statement.  What I really want is to override Equals in many scenarios so that it matches based on GetIdValue().

I know there is the GetIdValue() but I don't know how to write a function like that for the Excepts clause.

ie) listA.Except(listB) ... this calls the Equals which doesn't work when all I care about is a PK in both lists.

I really want listA.Except(listB where listA.GetIdValue() equals listB.GetIdValue()).

So I thought I would benefit from having a generic equals when all I care about is the PK.  Given that:

1) How do I create a generic equals override that I can put in my application level override of BusinessBase<T> ?

2) Can someone show me how I can write the Except statement to match based on GetIdValue()?

Thanks

jack

tmg4340 replied on Monday, November 30, 2009

Depending on your UI technology, writing a generic Equals override may not be possible.

I'm pretty sure Rocky touches on it in the 2008 book, but WPF and WinForms handle equality much differently.  IIRC, Equals won't work in WPF.  But not overriding them won't really work in WinForms.  In fact, I think Rocky says that if you're using WPF (and, I would assume, by extension Silverlight), you shouldn't override either method - though I think overriding "GetIdValue" won't hurt.

Having said that, building a generic "Equals" override that you can put into your base class should be easy enough - just reference the "GetIdByValue" method, and override that in your subclasses to return whatever you need.  It returns an object, so you can define your "object ID" however you want.

In terms of your Except method, Except can take an object that impments the generic IEqualityComparer interface.  So instead of worrying about overriding Equals, you could always create an object that implements that interface, passing your BusinessBase type as the generic type.  Then you just use that object in your Except (and several other LINQ method) calls.  You can still override "GetIdValue", and just reference that in your IEqualityComparer implementation.

HTH

- Scott

Copyright (c) Marimer LLC