简体   繁体   中英

c# What is this delegate within a sort

I don't understand the logic in the using delegate in this syntax. I'm looking for ways to sort a string and came across this...

 Array.Sort (thing, delegate (Things c1, Things c2)
            {
                return c1.Item.CompareTo(c2.Item); 
            }); 

For certain classes which belong to the .NET framework, like the String class and the classes which represent a number (int, float, decimal, ...), the delegate is optional because the interface IComparable (see @Idle_Mind answer) is already implemented.

You might define this delegate if you want to implement a special behaviour or if you want to use the comparison mechanism on a non-editable class which doesn't implement IComparable .

Considering you have to sort a string normally :

string s = "eabdfc"; //String to sort
char[] sa = s.ToCharArray(); //Convert to array
Array.Sort(sa); //Sort without any delegate
Console.WriteLine(new string(sa)); // The new string sorted

Considering you have to sort a string in the other direction, you can replace the Array.Sort line by :

Array.Sort(sa, (x, y) => x.CompareTo(y) * -1);

Why ? Because CompareTo must return :

  • -1 if element x < y
  • 0 if element x = y
  • 1 if element x > y

So, if you want to use Array.Sort with any classes you have to : either implement IComparable interface (if it's an user defined class), or define the delegate.

To sum up: the delegate offer more flexibility because we can write different behaviours at different places for the same class or the same object while IComparable offer a default behaviour for a class.

I hope my english is understandable, feel free to correct me.

The delegate, known as an anonymous function, allows you to declare a comparison mechanism without needing a completely separate function as below:

    private void button1_Click(object sender, EventArgs e)
    {
        Things t1 = new Things();
        t1.Item = "z";
        Things t2 = new Things();
        t2.Item = "a";

        Things[] things = new Things[]{ t1, t2};
        Array.Sort(things, CompareThings);

        foreach(Things t in things)
        {
            Console.WriteLine(t.Item);
        }
    }

    private int CompareThings(Things c1, Things c2)
    {
        return c1.Item.CompareTo(c2.Item);
    }

Here's an example on MSDN showing two versions of a sort, one with an anonymous function, and one with a declared function (as above).

As a side note, the explicit comparison of c1.Item to c2.Item is necessary because .Net doesn't know how it should compare one "Things" instance to another. If you implement the IComparable interface, however, then your code becomes cleaner as you don't need the anonymous or separate function:

public class Things : IComparable<Things>
{
    public string Item = "";

    int IComparable<Things>.CompareTo(Things other)
    {
        return this.Item.CompareTo(other.Item);
    }

}

Followed by:

    private void button1_Click(object sender, EventArgs e)
    {
        Things t1 = new Things();
        t1.Item = "z";
        Things t2 = new Things();
        t2.Item = "a";

        Things[] things = new Things[]{ t1, t2};
        Array.Sort(things); // <-- the intenal implementation of CompareTo() we added to class Things will be used!

        foreach(Things t in things)
        {
            Console.WriteLine(t.Item);
        }
    }

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