Writing a Better Comparison<T> for complex Ts

J

jehugaleahsa

Hello:

I find myself writing Comparison<T> delegates that looks like this:

private static int compareCustomers(Customer lhs, Customer rhs)
{
int result = Comparer<string>.Default.Compare(lhs.LastName,
rhs.LastName);
if (result == 0)
{
result = Comparer<string>.Default.Compare(lhs.FirstName,
rhs.FirstName);
}
return result;
}

Is this pretty standard?

This approach is fine up to the point where you have to compare more
than two or three fields.

Does anyone have a more elegant method for writing complex
Comparison<T>'s?

Thanks,
Travis
 
J

Jon Skeet [C# MVP]

I find myself writing Comparison<T> delegates that looks like this:

private static int compareCustomers(Customer lhs, Customer rhs)
{
int result = Comparer<string>.Default.Compare(lhs.LastName,
rhs.LastName);
if (result == 0)
{
result = Comparer<string>.Default.Compare(lhs.FirstName,
rhs.FirstName);
}
return result;
}

Is this pretty standard?

This approach is fine up to the point where you have to compare more
than two or three fields.

Does anyone have a more elegant method for writing complex
Comparison<T>'s?

In MiscUtil (http://pobox.com/~skeet/csharp/miscutil) we have a
ProjectionComparer and an extension method, so you can say:

IComparer<Customer> comparer =
ProjectionComparer.Create(cust => cust.LastName)
.ThenBy(ProjectionComparer.Create(cust => cust.FirstName));
etc

This could probably be beefed up even further with a bit of effort, to
be honest.
 
J

jehugaleahsa

In MiscUtil (http://pobox.com/~skeet/csharp/miscutil) we have a
ProjectionComparer and an extension method, so you can say:

IComparer<Customer> comparer =
    ProjectionComparer.Create(cust => cust.LastName)
       .ThenBy(ProjectionComparer.Create(cust => cust.FirstName));
etc

This could probably be beefed up even further with a bit of effort, to
be honest.

--
Jon Skeet - <[email protected]>
Web site:http://www.pobox.com/~skeet 
Blog:http://www.msmvps.com/jon_skeet
C# in Depth:http://csharpindepth.com- Hide quoted text -

- Show quoted text -

Stuck back in my 2.0 world, I have written this before:

private delegate int lameComparison();

private static int customerComparer(Customer lhs, Customer rhs)
{
lameComparison[] comparisons = {
delegate() { return
Comparer<string>.Default.Compare(lhs.LastName, rhs.LastName); },
delegate() { return
Comparer<string>.Default.Compare(lhs.FirstName, rhs.FirstName); },
};
int result = 0;
for (int i = 0; i != comparisons.Length && result == 0; ++i)
{
result = comparisons();
}
return result;
}

However, this not only makes my coworkers froth at the mouth, it has
performance hits (minimal).

One more reason to move to 3.0.

Thanks,
Travis
 

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