There is a sorting class in which you need to implement a benchmark, that is, the sorting time, but I get a type conversion error

class SelectionSort : ISort { public IEnumerable<T> Sort<T>(IEnumerable<T> inpurArray) { return Sort(inpurArray, Comparer<T>.Default); } public IEnumerable<T> Sort<T>(IEnumerable<T> inpurArray, IComparer<T> comparer) { //Cast to array var array = inpurArray.ToArray(); //pos_min is short for position of min int Min; //find the min element in the unsorted for (int i = 0; i < array.Length - 1; i++) { Min = i;//set pos_min to the current index of array //test against elements after j to find the smallest for (int j = i + 1; j < array.Length; j++) { if (comparer.Compare(array[j], array[Min]) > 0) { //pos_min will keep track of the index that min is in, this is needed when a swap happens Min = j; } } //if pos_min no longer equals i than a smaller value must have been found, so a swap must occur if (Min != i) { T temp = array[i]; array[i] = array[Min]; array[Min] = temp; } } return array; } public TimeSpan Benchmark<T>(IEnumerable<T> count) { var array = count.ToArray(); Random rand = new Random(); for (int x = 0; x < array.Length; x++) { array = new T [rand.Next(1, 500)]; } var time = Stopwatch.StartNew(); array = Sort(array, Comparer<T>.Default); time.Stop(); return time.Elapsed; } } 

Here in this place:

 array = Sort(array, Comparer<T>.Default); 

Tell me, what am I doing wrong and how to solve the problem? thank

  • Just add .ToArray() : array = Sort(array, Comparer.Default).ToArray(); - Dmitry D.
  • 2
    The code preceding the problem line is also puzzling. You are rebuilding an array in a loop. So conceived? - Dmitry D.
  • @DmitryD. I study, so I may not see mistakes, show me how you would have done, and where exactly did I make a mistake? Many thanks - Ethernets
  • @ DmitryD. You say array = new T [rand.Next (1, 500)] for this part ; What is the right way then ? because if you just write array = rand.Next (1, 500); I get an error - Ethernets
  • one
    Inside the Benchmark method - no way. Carry out the code for filling the array. And fill, for example, like this: array[x] = rand.Next(1, 500); - Dmitry D.

1 answer 1

You misinterpreted the error.
The compiler tells you that it cannot bring IEnumerable<T> to T[] , and not vice versa. Indeed, the Sort method returns IEnumerable<T> , and you are trying to assign the return value to a variable of type T[] .
Try .ToArray() return type to T[] calling .ToArray() :

 array = Sort(array, Comparer.Default).ToArray();