将ICollectionView转换为List<T>

16

我正在使用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<Call>


参考 https://dev59.com/o3VC5IYBdhLWcg3wxEN1 - nthpixel
4个回答

27

您可以尝试:

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

在使用CollectionViewSource获取视图上当前可见项目列表时,可以完美地工作。 - qJake
正如您在这里所看到的(https://dev59.com/WW865IYBdhLWcg3wCqHI),您可以使用`List<Call> CallsList = CallsView.OfType<Call>().ToList();`作为替代方案。 - h.m.i.13

1

我刚在Silverlight中遇到了这个问题,但是在WPF中是相同的:

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


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

0

你可以使用扩展方法来进行转换吗:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接