Custom sorting for entity collection?

Posts   
 
    
jnong
User
Posts: 9
Joined: 02-Feb-2007
# Posted on: 24-Jul-2008 22:38:14   

I'm trying to sort the UserEntity objects in the UserCollection by fields that are NOT null. Lets say my UserEntity has the following fields: FirstName, AlternateFirstName, LastName, AlternateLastName. The alternate first and last names can be null, but the first and last names will always contain a value.

I need to programmatically populate a TreeView with TreeNodes created from these UserEntity objects, and have them be sorted using the logical "Last name, First name" order. The last name will be the value LastNameAlternate field if it is NOT null, otherwise the LastName field is used. Same for the first name.

I tried to use a SortExpression in the GetMulti() method when retrieving from the database, but somehow it doesn't sort correctly. My code for the SortExpression is:

SortExpression sorter = new SortExpression(); sorter.Add(UserFields.AlternateLastName | SortOperator.Ascending); sorter.Add(UserFields.LastName | SortOperator.Ascending); sorter.Add(UserFields.AlternateFirstName | SortOperator.Ascending); sorter.Add(UserFields.FirstName | SortOperator.Ascending);

So now I'm looking for a way to sort the collection after retrieval from the database. Looks like I have 3 ways to try to implement this customized sorting:

1) Find a way to sort the objects within the collection in memory. 2) Create a SortableUserEntity class that inherits from UserEntity and implement the IComparable interface. I can then use an ArrayList to store and sort these objects. 3) Create a SortableTreeNode class that inherits from TreeNode and implement the IComparable interface. I can then use an ArrayList to store and sort these nodes.

Which is the best way? Please give me some suggestions for how as well. Thanks.

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 25-Jul-2008 05:57:23   

What I would probably do is:

  1. Write a custom entity property that represent the non-null field you want to sort.
public partial class UserEntity
{
    public string MyCustomLastName
    {
        get
        {
            return (!string.IsNullOrEmpty(AlternateLastName)) ? AlternateLastName : LastName;
        }
    }
}
  1. Then you can sort in-memory based on that custom property:
// create a view based on the fetched collection
EntityView2<UserEntity> usersSortedView = new EntityView2<UserEntity>(fetchedCollection);

// apply the sorter
SortExpression sorter = new SortExpression();
sorter.Add(new EntityProperty("MyCustomLastName") | SortOperator.Ascending);
customersView.Sorter = sorter;

Do the same for the rest of fields you want to sort and you should make it wink . A workaround would be use LINQ2LLBL (v2.6) to fetch the sorted collection, or use LINQ2OBJECTS to sort in-memory.

Let us know if we can help you further.

David Elizondo | LLBLGen Support Team