在List< T>的.sort()方法,是一项前所未有相比,本身? [英] In the List<T>.Sort() method, is an item ever compared to itself?

查看:164
本文介绍了在List< T>的.sort()方法,是一项前所未有相比,本身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在一个自定义的IComparer传递给列表的排序的一个实例()方法,将比较器的比较(X,Y)的方法永远是同一项目叫什么名字?

If I pass in a custom IComparer to an instance of a List's Sort() method, will the comparer's Compare(x,y) method ever be called with the same item?

IE浏览器。难道比较(X,X)可称为

ie. Is it possible that Compare(x,x) may be called.

编辑:更多感兴趣的情况下列表项的是不同的。

More interested in the case where items of the list are distinct.

推荐答案

我写了一个测试程序来尝试一下。它看起来像它实际上确实的比较()相同的元素本身(至少是比较()被调用同一项目两次)。在这个方案中,比较()被调用,参数(2,2)

I wrote a test program to try it out. It looks like it actually does Compare() the same element to itself (at least Compare() is called for the same item twice). In this program, Compare() is called with arguments (2, 2).

using System;
using System.Collections.Generic;

static class Program
{
    class MyComparer : Comparer<int>
    {
        public override int Compare(int x, int y)
        {
            Console.WriteLine("Compare(" + x + ", " + y + ")");
            if (x < y) return -1;
            if (x > y) return 1;
            return 0;
        }
    }

    static void Main()
    {
        MyComparer comparer = new MyComparer();
        List<int> list = new List<int> { 1, 2, 3 };
        list.Sort(comparer);
        return;

    }
}

和输出为:

Compare(1, 2)
Compare(1, 3)
Compare(2, 3)
Compare(1, 2)
Compare(2, 2)
Compare(2, 3)
Compare(2, 2)

这篇关于在List&LT; T&GT;的.sort()方法,是一项前所未有相比,本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆