I'm using a GridView with the SelectionMode set to Multiple. I select a few items, then on my button click event, I want to process those selected items.
I'm able to grab the collection of these items with the GridView.SelectedItems property, and treat this as a generic list. I want to be able to treat this as a list of the type of underlying objects within that list.
I can validate all the items in the list are of the correct type:
if(items.Any(item => !(item is MyType))) throw new ArgumentException("Invalid list of items");
But what I'm unable to do is treat that list as anything other than a list of objects. For example:
items is IList<object> = true
items is IEnumerable<object> = true;
however
items is IList<MyType> = false
items is IEnumerable<MyType> = false
such that something like return (items as List<MyType>)
fails
Short of enumerating the list and creating a new one of type MyType
I'm at a loss.
var myItems = new List<MyItem>(items.Count);
foreach (var item in items)
{
myItems.Add(item as MyItem);
}
any tips?
list.Cast<MyType>()
will throw exception if any single element is not of given typelist.OfType<MyType>()
will filter out by give typeAlso:
list.Count() != list.OfType<MyType>()
will iterate sequence twice if it doesn't implement IList
, i.e. is pure enumerator and not List or Array