In my app, I have several comparison methods. I would like the user to be able to select the sorting method to use. Ideally, I would like to set a delegate and it is updated based on the user’s selection. This way, I can keep the code generic using List.Sort(delegate).
This is my first time attempting to use C# delegates and I’m running into syntax errors. Here is what I have so far:
The delegate:
private delegate int SortVideos(VideoData x, VideoData y);
private SortVideos sortVideos;
In the class constructor:
sortVideos = Sorting.VideoPerformanceDescending;
The comparison method in the public static Sorting class (which works when I call it directly):
public static int VideoPerformanceDescending(VideoData x, VideoData y)
{
*code statements*
*return -1, 0, or 1*
}
Failed syntax that complains of “some invalid arguments”:
videos.Sort(sortVideos);
Ultimately, I would like to change “sortVideos” to point to the method of choice. “videos” is a list of type VideoData. What am I doing wrong?
The
List<T>accepts a delegate of typeComparison<T>so you cannot define your own delegate, you just need to reuse the delegateComparison<T>.Expanding the answer to also contemplate the user selection part, you could store the available options in a dictionary and then in the UI allow the user to select the sort algorithm by selecting the key to the dictionary.