1

Im wondering if its possible to reuse my overload of the Sort(Comparison) method to sort both labels and textboxes by tabIndex. Ive already tried and i couldnt get it to work. Any help would be appreciated.

foreach(Control control in gbUserInputs.Controls)
        {
            if (control is Label)
            {
                inputLabels.Add((Label)control);
            }

            if (control is TextBox)
            {
                inputTxtboxes.Add((TextBox)control);
            }
        }

Sort method call(this doesnt work).

inputLabels.Sort(sortMyInputs<Label>);

Overload of sort method.

private static int sortMyInputs<T>(T entry1, T entry2)
    {
        return entry1.TabIndex.CompareTo(entry2.TabIndex);
    }
Hans Rudel
  • 3,053
  • 5
  • 35
  • 57

1 Answers1

1

You shouldn't be making a generic method:

private static int CompareLabels(Label entry1, Label entry2)
{
    return entry1.TabIndex.CompareTo(entry2.TabIndex);
}

The point of a generic delegate is to allow it to hold methods of different concrete types; not to allow it to hold methods that are themselves generic.

If you want to reuse your method, you can modify it to take Control (which both TextBox and Label inherit); you would still be able to pass it to List<Label>.Sort because of delegate covariance.


If you're using .Net < 4, which doesn't have delegate covariance, you can do it your way by adding a constraint to the method so that it knows what T can be:

private static int CompareLabels<T>(T entry1, T entry2) where T : Control
{
    return entry1.TabIndex.CompareTo(entry2.TabIndex);
}

You can also simply replace all of your code with one line of LINQ:

inputLabels = gbUserInputs.Controls.OfType<Label>()
                                   .OrderBy(c => c.TabIndex)
                                   .ToList();
SLaks
  • 800,742
  • 167
  • 1,811
  • 1,896
  • Sorry for what is probably a stupid question, but where does the generic delegate come into this? I havent covered LINQ's yet but thanks for including that. Yes im using .net 4.0. Thanks for your help so far – Hans Rudel May 31 '12 at 12:05
  • @HansRudel: `Sort()` takes a `Comparison`, which is a generic delegate. – SLaks May 31 '12 at 12:06
  • I highly recommend that you learn LINQ; it makes this kind of code substantially shorter and much more readable. (and is usually faster too) – SLaks May 31 '12 at 12:07
  • yeah ok... D'oh. Its on my list of things to do but there are still a few of the basics that im not 100% upto speed with. Thanks very much for taking the time to answer my question, i really appreciate it! – Hans Rudel May 31 '12 at 12:07