简体   繁体   中英

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 ?

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 !

除了@Jamiec答案,您还可以使用LINQ对数组进行排序-

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM