【发布时间】:2021-06-08 09:35:35
【问题描述】:
我有一个非常大的集合,2000++ 个 SVG 图像,用户需要根据需要进行过滤。过滤是通过文本字段完成的,所以我用 LINQ 做一个简单的ObservableCollection 过滤器:
async void SearchChanged(System.Object sender, Xamarin.Forms.TextChangedEventArgs e)
{
SearchableImages.Clear(); // ObservableCollection
if (Search.Text.Length < 3) return;
// ImageCollection is an always in-memory List<ImageItem>
var filter = await Task.FromResult<IEnumerable<ImageItem>>(
ImageCollection.Where((i) => i.Name.Contains(Search.Text.ToLower()))
);
foreach (var p in filter)
SearchableImages.Add(p);
}
此代码运行非常缓慢,以至于您可以在那里看到 if 块,将搜索字段的长度限制为 3。启用搜索任意长度的字符会使其无法使用。
显然Filter property of a CollectionView 不可用:
<CollectionView x:Name="CollectionList" ItemsSource="{Binding SearchableIcons}" ...>
string src = Search.Text.ToLower();
CollectionList.Filter = (item) => item.Name.Contains("hello");
Error CS1061: 'CollectionView' does not contain a definition for 'Filter' and no accessible extension method 'Filter' accepting a first argument of type 'CollectionView' could be found (are you missing a using directive or an assembly reference?) (CS1061)
如何平滑地过滤大量图像?
【问题讨论】:
-
我真的无法想象过滤包含 2000 个项目的列表会花费很长时间。真的是过滤器这么慢吗?或者可能是显示图像的 UI?
-
我对 Xamarin 不是很熟悉,但是 ObservableCollection 在每次添加时都会触发一个 chenged 事件。也许说
SearchableImages = new(filter)会更快? -
除了其他评论者提出的优秀观点之外,每次用户键入字符时,您都会运行此代码
-
感谢所有 cmets,这非常有帮助!我很困惑,因为过滤器不可用,显然问题已经更新了。
标签: c# xamarin xamarin.forms