Sorting objects on multiple properties

T

Trey Bean

So I'm getting an array of objects from a web service. Before
presenting this array to the user, I need to sort these objects by two
of it's properties. Basically, each property has a date and a type. I
would like to bind this to a grid in the form of

11/21/2006 - Type1
11/21/2006 - Type1
11/22/2006 - Type1
11/24/2006 - Type1
11/22/2006 - Type2
11/23/2006 - Type2
11/24/2006 - Type3

I know how you use IComparer to sort the array on either one of the
properties, but how do I sort/group on both?

I should mention that the data comes from the web service ordered by
date, but once I sort by type it loses that order naturally.

My IComparer class is this:

public class typeComparerClass : IComparer
{
int IComparer.Compare(Object x, Object y)
{
Action action_1;
Action action_2;

if (x is Action)
{
action_1 = (Action)x;
}
else
{
throw new ArgumentException("Object is not of type
Action");
}

if (y is Action)
{
action_2 = (Action)y;
}
else
{
throw new ArgumentException("Object is not of type
Action");
}

return action_1.actionType.CompareTo(action_2.actionType);
}
}
 
T

Trey Bean

Nevermind, I figured it out.

I added a condition after performing the first CompareTo--if the types
are equal, compare using dates.

public class typeComparerClass : IComparer
{
int IComparer.Compare(Object x, Object y)
{
Action action_1;
Action action_2;

if (x is Action)
{
action_1 = (Action)x;
}
else
{
throw new ArgumentException("Object is not of type
Action");
}

if (y is Action)
{
action_2 = (Action)y;
}
else
{
throw new ArgumentException("Object is not of type
Action");
}

int type_compare =
action_1.actionType.CompareTo(action_2.actionType);

if (type_compare == 0)
{
return action_1.startTS.CompareTo(action_2.startTS);
}
else
{
return type_compare;
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top