我正在使用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
类型的新列表,我就不知所措了。
var myItems = new List<MyItem>(items.Count);
foreach (var item in items)
{
myItems.Add(item as MyItem);
}
任何提示?
答案 0 :(得分:4)
试
items.Cast<MyType>()
答案 1 :(得分:2)
list.Cast<MyType>()
将抛出异常
list.OfType<MyType>()
将按赠送类型此外:
list.Count() != list.OfType<MyType>()
如果没有实现IList
,将迭代序列两次,即纯枚举器而不是List或Array