问题描述:

How do i get the number of elements of a dynamic object returned by Enumerable.Except()?

Look:

dynamic itensToRemove = Enumerable.Except(currentCollection, newCollection);

dynamic itensToAdd = Enumerable.Except(newCollection, currentCollection);

When i try to do this:

for (int i = 0; i < itensToRemove.Count(); i++)

I got the runtime error 'object does not contain a definition for Count', so, how i can i got the number of elements?

网友答案:

dynamic doesn't resolve extension methods, which is why you've explicitly got calls to Enumerable.Except. Do the same thing for Count:

// You don't want to do this on every iteration!
int count = Enumerables.Count(itemsToRemove);
for (int i = 0; i < count; i++)

It's not clear why you'd want to use that in a for loop though - it would be more normal to use it in a foreach loop. You may also want to consider using ToList to make sure you evaluate the query once:

dynamic itemsToRemoveList = Enumerable.ToList(itemsToRemove);
相关阅读:
Top