提供列表排序视图的任何类

本文关键字:排序 视图 任何类 列表 | 更新日期: 2023-09-27 18:31:58

.NET 中是否有一个类可以用作List<T>的只读有序视图?与DataView必须DataTable List<T>具有相同关系的东西,以便我可以配置我希望对此视图进行排序的属性,然后视图将监视列表并在将项目添加到/从列表中删除时自动更新自身。

:注:每次需要迭代列表时,我都可以使用 LINQ 的OrderBy来执行此操作,但查看我需要迭代的次数,这看起来有些矫枉过正。

编辑:DataView(据我所知)不会每次都重新创建表行的有序副本。它采用构造函数中的排序列名称,然后密切关注底层DataTable的更改并动态更新自身,而不是在迭代视图时从头开始重新创建视图。

提供列表<T>排序视图的任何类

对于集合的单独ViewModel(因此您可以将同一集合的不同"形状"呈现给调用方),BCL 中没有任何内容,我也不知道。所以你必须自己建造它。但是为了跟踪集合中的更改(注意,而不是该集合中的对象),您可以使用 ObservableCollection

可以使用可视化控件对数据进行排序或筛选:

<Window x:Class="ListBoxSort_snip.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="ListBoxSort_snip" Height="300" Width="300">
    <DockPanel>
      <ListBox Name="myListBox" DockPanel.Dock="Top">
        <ListBoxItem>my</ListBoxItem>
        <!--Or you can set the content this way:-->
        <!--<ListBoxItem Content="my"/>-->
        <ListBoxItem>1</ListBoxItem>
        <ListBoxItem>Sort</ListBoxItem>
        <ListBoxItem>3</ListBoxItem>
        <ListBoxItem>ListBox</ListBoxItem>
        <ListBoxItem>2</ListBoxItem>
      </ListBox>
      <Button Click="OnClick" Width="30" Height="20" DockPanel.Dock="Top">Sort</Button>
    </DockPanel>
</Window>
private void OnClick(object sender, RoutedEventArgs e)
{
    myListBox.Items.SortDescriptions.Add(
        new SortDescription("Content", ListSortDirection.Descending));
}

请参阅文章 - 如何:对视图中的数据进行排序,了解详细信息。

你也许可以使用SortedList .

它有一个SortedList(IComparer)构造函数,您可以将自定义比较器传递给该构造函数,该比较器定义要排序的字段。