user1765862
user1765862

Reputation: 14165

IComparer interface, compare many objects not just two instances

I'm following examples Apress pro c# framework and I have question on IComparer interface If I want to create some custom comparer which will compare my objects by name I should implement IComparer interface so I have following

public class CarNameComparer : IComparer
    {
        int IComparer.Compare(object obj1, object obj2)
        {
            Car temp1 = obj1 as Car;
            Car temp2 = obj2 as Car;
            if (temp1 != null && temp2 != null)
            {
                return String.Compare(temp1.Name, temp2.Name);                
            }
            else
            {
                throw new ArgumentException("Parameter is not a Car");
            }
        }
    }

And I'm calling to compare like this

Array.Sort(italianCars, new CarNameComparer());

Which is fine, but this approach is comparing only two instances, as far as I can see this is a limited usage. What if I want to compare bunch of objects, not just two of them ?

Upvotes: 1

Views: 413

Answers (3)

Rohit Vats
Rohit Vats

Reputation: 81253

In addition to @Jamiec answer, you can sort the array using LINQ -

italianCars.OrderBy(car => car.Name);

Upvotes: 2

Jamiec
Jamiec

Reputation: 136154

You're misunderstanding the use of the Comparer. It will still sort the array even if there are a thousand instances of Car. It just does it by comparing two at a time!

Upvotes: 8

Related Questions