Вставка элемента в SortableBindingList - PullRequest
0 голосов
/ 04 апреля 2019

У меня есть WinForms DataGridView, привязанный к списку SortableBindlingList (очень похоже на в этом примере ).

По умолчанию при добавлении элементов они отображаются в нижней части DataGridView. В примерах, с которыми я сталкивался, люди хотели, чтобы новые элементы отображались в правильной отсортированной позиции, которую они называли DataGridView.Sort после добавления в элемент.

Мне кажется, это довольно дорого, если у вас большой набор данных и элементы часто добавляются. Является ли добавление следующего метода в SortableBindingList хорошей идеей? Любые идеи о том, как сделать это быстрее или надежнее?

public int InsertSorted(T newItem)
{
    PropertyDescriptor prop = sortPropertyValue;
    ListSortDirection direction = sortDirectionValue;
    Type interfaceType = prop.PropertyType.GetInterface("IComparable");

    if (interfaceType == null && prop.PropertyType.IsValueType)
    {
        Type underlyingType = Nullable.GetUnderlyingType(prop.PropertyType);

        if (underlyingType != null)
        {
            interfaceType = underlyingType.GetInterface("IComparable");
        }
    }

    if (interfaceType != null)
    {
        IComparable comparer = (IComparable)prop.GetValue(newItem);

        IList<T> query = base.Items;
        int idx = 0;
        if (direction == ListSortDirection.Ascending)
        {
            for (idx = 0; idx < query.Count - 1; idx++)
            {
                if (comparer.CompareTo(prop.GetValue(query[idx])) < 0)
                {
                    break;
                }
            }
        }
        else
        {
            for (idx = 0; idx < query.Count - 1; idx++)
            {
                if (comparer.CompareTo(prop.GetValue(query[idx])) > 0)
                {
                    break;
                }
            }
        }

        this.InsertItem(idx, newItem);
        return idx;
    }
    else
    {
        throw new NotSupportedException("Cannot sort by " + prop.Name +
            ". This" + prop.PropertyType.ToString() +
            " does not implement IComparable");
    }
}
...