By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
460,023 Members | 1,297 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 460,023 IT Pros & Developers. It's quick & easy.

Using ICompare to sort on two properties

P: n/a
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);

}

}
Nov 16 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a

"MFRASER" wrote...
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
Nov 16 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.