![](/img/trans.png)
[英]Extension method on ObservableCollection<MyType>, MyType : IEnumerable<MyType>
[英]Converting SelectedItems to IEnumerable<MyType>
我正在使用GridView,其中SelectionMode设置为Multiple。 我选择了一些项目,然后在我的按钮单击事件上,我要处理那些选定的项目。
我可以使用GridView.SelectedItems属性获取这些项目的集合,并将其视为通用列表。 我希望能够将其视为该列表中基础对象类型的列表。
我可以验证列表中的所有项目的类型正确:
if(items.Any(item => !(item is MyType))) throw new ArgumentException("Invalid list of items");
但是我无法做的是将该列表视为对象列表以外的任何东西。 例如:
items is IList<object> = true
items is IEnumerable<object> = true;
然而
items is IList<MyType> = false
items is IEnumerable<MyType> = false
这样像return (items as List<MyType>)
失败
缺少枚举列表并创建MyType
类型的新列表的问题我很MyType
。
var myItems = new List<MyItem>(items.Count);
foreach (var item in items)
{
myItems.Add(item as MyItem);
}
有小费吗?
尝试
items.Cast<MyType>()
list.Cast<MyType>()
将引发异常 list.OfType<MyType>()
将按给定类型过滤 也:
list.Count() != list.OfType<MyType>()
如果不实现IList
,则将序列两次迭代,即它是纯枚举器,而不是List或Array
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.