Сортировка List: "ошибка при сравнении двух элементов массива." - C#
Формулировка задачи:
Имеется примерно такой код:
Сортировка говорит "ошибка при сравнении двух элементов массива." Как правильно сделать сортировку по value?
Посмотрел кое-что на форуме, попытался сделать так
Но VS пишет неправильный возвращаемый тип.
struct aBox
{
public int index;
public double value;
}
List<Box>.sort() static double MyComparer(activeSpell x, activeSpell y)
{
return x.value - y.value;
}
List<Box>.sort(MyComparer); Решение задачи: «Сортировка List: "ошибка при сравнении двух элементов массива."»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SortingTest
{
class Program
{
static void Main(string[] args)
{
List<Test> testList = new List<Test>
{
new Test(){intValue=1, stringValue="One"},
new Test(){intValue=5, stringValue="Seven"},
new Test(){intValue=0, stringValue="Six"},
new Test(){intValue=3, stringValue="Five"},
new Test(){intValue=4, stringValue="One"}
};
//Простой вывод элементов листа
foreach (Test t in testList)
{
Console.WriteLine(t);
}
//Сортируем через метод Sort по значению свойства intValue
testList.Sort();
Console.WriteLine();
//Вывод отсортированного
foreach (Test t in testList)
{
Console.WriteLine(t);
}
//Сортируем по свойству stringValue через дополнительный класс-сортировщик
testList.Sort(new TestComparer());
Console.WriteLine();
//Вывод отсортированного
foreach (Test t in testList)
{
Console.WriteLine(t);
}
Console.ReadLine();
}
}
public class Test:IComparable<Test>
{
public int intValue { get; set; }
public string stringValue { get; set; }
public int CompareTo(Test other)
{
if (this.intValue > other.intValue)
return 1;
if (this.intValue < other.intValue)
return -1;
else
return 0;
}
public override string ToString()
{
return string.Format("intValue: {0}, stringValue: {1}", intValue, stringValue);
}
}
public class TestComparer : IComparer<Test>
{
public int Compare(Test x, Test y)
{
if (x.stringValue.Length > y.stringValue.Length)
return 1;
if (x.stringValue.Length < y.stringValue.Length)
return -1;
else
return 0;
}
}
}