Using ICompare to sort on two properties

M

MFRASER

How do I setup my ICompare to sort on two properties?

/// <summary>

/// Compares two objects and returns a value indicating whether one is less
than, equal to or greater than the other.

/// </summary>

/// <param name="x">UserName</param>

/// <param name="y">UserName</param>

/// <returns></returns>

public string Compare(object x, object y)

{

UserName UserName X = (UserName )x;

UserName MapItemY = (UserName )y;

switch (m_Column)

{

case UserName .UserName SortColumns.FNameLName:

{

switch (m_SortOrder)

{

case Common.SortOrderTypes.Ascending:

//Not sure how to setup the compare to compare two properties

return UserNameX.?.CompareTo(UserNameY.?);

case Common.SortOrderTypes.Descending:

return UserNameY.?.CompareTo(UserNameX.?);


}

break;

}

case MapItem.MapItemSortColumns.LNameFName:

{

switch (m_SortOrder)

{

case Common.SortOrderTypes.Ascending:

//Not sure how to setup the compare to compare two properties

return UserNameX.?.CompareTo(UserNameY.?);

case Common.SortOrderTypes.Descending:

return UserNameY.?.CompareTo(UserNameX.?);



}

break;

}

}

return UserNameX.ItemKey.CompareTo(UserNameY.ItemKey);

}

}
 
B

Bjorn Abelli

...
How do I setup my ICompare to sort on two properties?

That depends on which property is the most "significant".

If there's a "difference" when you compare the most significant property,
return that result.

If they're "equal", compare the other property and return that result.

BTW, the Compare method should return an int, not a string...

Example:


public int Compare(object x, object y)
{
Person userX = (Person) x;
Person userY = (Person) y;

if ( userX.LastName.Equals(userY.LastName) )
{
return userX.FirstName.CompareTo(userY.FirstName);
}

return userX.LastName.CompareTo(userY.LastName);
}


// Bjorn A
 

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