将ICollectionView转换为列表< >

本文关键字:列表 ICollectionView 转换 | 更新日期: 2023-09-27 18:03:54

我正在将ICollectionView的属性类型绑定到WPF, . net 4.0的DataGrid控件上。

我在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)
    {
       //..
    }

Init ICollection view:

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

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

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

我想将ICollection当前视图转换为IList<Call>

将ICollectionView转换为列表< >

您可以尝试:

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

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

IEnumerable<call> calls = collectionViewSource.View.Cast<call>();

因为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>();

您可以使用扩展方法来转换:

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