c# - 将项目插入到 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");
}
}
解决方案
推荐阅读
- swiftui - SwiftUI - 我如何在 WatchOS 中像 Podcasts 应用程序一样创建堆栈选择器?
- javascript - ./src/firebase.js 未找到模块:无法解析 'D:\Coding\fb-clone\src' 中的 'firebase'
- powershell - 如何从 PowerShell 脚本打开文件夹浏览器对话框?
- apache-spark - Spark Sort Merge Join 是否涉及洗牌阶段?
- excel - 日期格式挑战
- typescript - React Native Firebase 应用程序中的 GoogleSignIn 不起作用
- sql - 表规则中的规则 ID,其中 item 和 dc 被停用
- r - 如何计算按列名分组的数据框/矩阵中的平均值和标准差
- .htaccess - 将链接转发到同一链接但在子域上的最佳方法是什么?
- azure-functions - 添加 Azure 存储 Blob 容器输入绑定 Azure Functions Java