для моего проекта. Мне нужно иметь наблюдаемый коллектив, который может сортировать баллы каждый раз, когда мы добавляем новые очки. Просмотрев ищу идеи я чувствовал на превосходном исходный коде (ссылка http://www.dotmaniac.net/simple-sorted-observablecollection/.)Используйте производный класс ObservableCollection
Идея заключается в том, чтобы переопределить функции от ObservableCollection класса
public class SortedPoints<T>
: ObservableCollection<T> where T : IComparable<T> {
protected override void InsertItem(int index, T item)
{
if (this.Count == 0)
{
base.InsertItem(0, item);
return;
}
index = Compare(item, 0, this.Count - 1);
base.InsertItem(index, item);
}
private int Compare(T item, int lowIndex, int highIndex)
{
int compareIndex = (lowIndex + highIndex)/2;
if (compareIndex == 0)
{
return SearchIndexByIteration(lowIndex, highIndex, item);
}
int result = item.CompareTo(this[compareIndex]);
if (result < 0)
{ //item precedes indexed obj in the sort order
if ((lowIndex + compareIndex) < 100 || compareIndex == (lowIndex + compareIndex)/2)
{
return SearchIndexByIteration(lowIndex, compareIndex, item);
}
return Compare(item, lowIndex, compareIndex);
}
if (result > 0)
{ //item follows indexed obj in the sort order
if ((compareIndex + highIndex) < 100 || compareIndex == (compareIndex + highIndex)/2)
{
return SearchIndexByIteration(compareIndex, highIndex, item);
}
return Compare(item, compareIndex, highIndex);
}
return compareIndex;
}
/// <summary>
/// Iterates through sequence of the collection from low to high index
/// and returns the index where to insert the new item
/// </summary>
private int SearchIndexByIteration(int lowIndex, int highIndex, T item)
{
for (int i = lowIndex; i <= highIndex; i++)
{
if (item.CompareTo(this[i]) < 0)
{
return i;
}
}
return this.Count;
}
/// <summary>
/// Adds the item to collection by ignoring the index
/// </summary>
protected override void SetItem(int index, T item)
{
this.InsertItem(index, item);
}
private const string _InsertErrorMessage
= "Inserting and moving an item using an explicit index are not support by sorted observable collection";
/// <summary>
/// Throws an error because inserting an item using an explicit index
/// is not support by sorted observable collection
/// </summary>
[Obsolete(_InsertErrorMessage)]
public new void Insert(int index, T item)
{
throw new NotSupportedException(_InsertErrorMessage);
}
/// <summary>
/// Throws an error because moving an item using explicit indexes
/// is not support by sorted observable collection
/// </summary>
[Obsolete(_InsertErrorMessage)]
public new void Move(int oldIndex, int newIndex)
{
throw new NotSupportedException(_InsertErrorMessage);
}
}
Проблемой является У меня нет идеи, как использовать ее с моими объектами. Моих объектов являются класс RofPoints
public class RofPoints : IComparable
{
[DisplayName("X")]
[Description("Punkte der X axis")]
public int X { get; set; }
[DisplayName("Y")]
[Description("Punkte auf der Y Achse")]
public int Y { get; set; }
private double dx;
[DisplayName("dX")]
[Description("Punkte auf der X Achse mit double values")]
public double dX
{
get
{
return dx;
}
set
{
dx = value;
}
}
private double dy;
[DisplayName("dY")]
[Description("Punkte auf der Y Achse mit double values")]
public double dY
{
get
{
return dy;
}
set
{
dy = value;
}
}
public override string ToString()
{
return X + "/" + Y;
}
public double CompareTo(double dX)
{
return this.dX;
}
public int CompareTo(object obj)
{
return dx.CompareTo(obj);
}
}
}
Я хотел бы использовать класс SortedPoints, чтобы каждый новый rofpoints добавил упорядоченные после атрибута оГо.
Когда я пишу где-то в Кодексе:
SortedPoints<RofPoints> listofpoints = new SortedPoints<RofPoints>
, который не работает, потому что компилятор не может преобразовать неявно IComparable. У меня нет идеи, как идти дальше. Не могли бы вы объяснить мне, как использовать его или дать мне пример?
Я не могу дать больше кода, потому что я действительно заблокирован.
Большое спасибо за ответ. Я попытался реализовать метод сравнения в классе RofPoints, но он ничего не меняет. – littlecloud47
Метод CompareTo 'RofPoints' должен возвращать -1,0 или 1 в зависимости от того, какой объект больше. Итак, сначала вы должны объяснить, когда объект «RofPoints» больше, чем другой. (Больше, если X больше, если Y больше, в зависимости от функции по этим 2 значениям ....?) – Pikoh