Casting to an IEnumerable
I have a rather long bit of code I use to count the number of objects in a list that have one of their properties set to a certain value. However, nearly everything I mentioned above gets passed in at run time, leaving me with this:
((List<MyObject>)this.DataSource).Count(d => d.GetType().GetProperty(MyProperty).GetValue(d, null).ToString() == ValueToMatch);
The problem is that the list is stored as an object in the Datasource property. In order to use count, currently I have to cast this object to a list of type MyObject. I'd like to be able to store any kind of IEnumerable in DataSource. I know that the object stored in Datasource will always be a List, but I'm having trouble con开发者_JAVA技巧vincing C# of this fact. It keeps grumbling about type safety.
I'm in .Net 3.5, so upcasting to a List< Object > fails at run time due to co/contravariance (I can never remember which one is which). I similarly cannot cast to an IEnumerable. Is there any way to make this piece of code work with any kind of IEnumerable?
How about this:
((IEnumerable)this.DataSource).Cast<object>().Count(d => d.GetType().GetProperty(MyProperty).GetValue(d, null).ToString() == ValueToMatch);
Enumerable.Cast
is one of the few extension methods that works on the non-generic IEnumerable
. It returns an IEnumerable<T>
after which you can use the other extension methods like Enumerable.Count
.
Would ((IEnumerable)DataSource).Cast<object>()
not work?
精彩评论