【问题标题】:Convert ICollectionView to List<T>将 ICollectionView 转换为 List<T>
【发布时间】:2011-10-15 03:02:46
【问题描述】:

我正在 WPF、.NET 4.0 中的 DataGrid 控件上绑定 ICollectionView 的属性类型。

我在ICollectionView 上使用Filter

    public ICollectionView CallsView
    {
        get
        {
            return _callsView;
        }
        set
        {
            _callsView = value;
            NotifyOfPropertyChange(() => CallsView);
        }
    }

    private void FilterCalls()
    {
        if (CallsView != null)
        {
            CallsView.Filter = new Predicate<object>(FilterOut);
            CallsView.Refresh();
        }
    }

    private bool FilterOut(object item)
    {
       //..
    }

初始化 ICollection 视图:

IList<Call> source;
CallsView = CollectionViewSource.GetDefaultView(source);

我正在尝试解决这个问题:

例如源数据计数为 1000 项。我使用过滤器,在 DataGrid 控件中我只显示 200 项。

我想将ICollection 当前视图转换为IList&lt;Call&gt;

【问题讨论】:

标签: c# list datagrid icollectionview


【解决方案1】:

因为System.Component.ICollectionView 没有实现IList,所以不能只调用ToList()。就像 Niloo 已经回答的那样,您首先需要在集合视图中投射项目。

您可以使用以下扩展方法:

/// <summary>
/// Casts a System.ComponentModel.ICollectionView of as a System.Collections.Generic.List&lt;T&gt; of the specified type.
/// </summary>
/// <typeparam name="TResult">The type to cast the elements of <paramref name="source"/> to.</typeparam>
/// <param name="source">The System.ComponentModel.ICollectionView that needs to be casted to a System.Collections.Generic.List&lt;T&gt; of the specified type.</param>
/// <returns>A System.Collections.Generic.List&lt;T&gt; that contains each element of the <paramref name="source"/>
/// sequence cast to the specified type.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <c>null</c>.</exception>
/// <exception cref="InvalidCastException">An element in the sequence cannot be cast to the type <typeparamref name="TResult"/>.</exception>
[SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Justification = "Method is provided for convenience.")]
public static List<TResult> AsList<TResult>(this ICollectionView source)
{
    return source.Cast<TResult>().ToList();
}

用法:

var collectionViewList = MyCollectionViewSource.View.AsList<Call>();

【讨论】:

    【解决方案2】:

    你可以试试:

    List<Call> CallsList = CallsView.Cast<Call>().ToList();
    

    【讨论】:

    • 在使用 CollectionViewSource 获取视图中当前可见项目的列表时完美运行。
    【解决方案3】:

    我刚刚在 Silverlight 中遇到了这个问题,但在 WPF 中也是这样:

    IEnumerable&lt;call&gt; calls = collectionViewSource.View.Cast&lt;call&gt;();

    【讨论】:

      【解决方案4】:

      你能不能只用扩展方法来转换:

      IList<Call> source = collection.ToList();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-26
        • 2012-02-24
        • 2012-02-14
        • 1970-01-01
        • 2021-12-02
        相关资源
        最近更新 更多