首页 > 解决方案 > 将项目插入到 SortableBindingList

问题描述

我有一个绑定到 SortableBindlingList 的 WinForms DataGridView(与此示例非常相似)。

默认情况下,添加项目时,它们将显示在 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");
    }
}

标签: c#datagridviewbindinglist

解决方案


推荐阅读