0

The ListItems has one item which always gives type mismatch exception. The code line 'MyItem items in ListItems' cause the exception to raise as there is some type mismatch between Listitems and MyItem. How do I ignore the type mismatch exception and move to the next element. If it would enter inside the foreach loop, I could have used the 'continue'. But the code does not even enter the for each loop

foreach (MyItem items in ListItems)
{
   ...Do...
}

2 Answers 2

6

I would recommend using IEnumerable.OfType. This is like using an is MyItem test on each item, and only selecting - and thus looping over - the items where such a test is true. (It actually also performs a cast, which ensures the excepted result sequence type, but only if it can.)

foreach (var items in ListItems.OfType<MyItem>()) {
   // items not "of" MyItem will be skipped
}

On the other hand, the original code is like a direct (MyItem) cast on each item, which can fail with a InvalidCastException.

Sign up to request clarification or add additional context in comments.

Comments

4

You need to filter out so only the MyItem items are processed. Be sure to include the System.Linq namespace and do

foreach (MyItem items in ListItems.OfType<MyItem>())
{
   ...Do...
}

That will filter your list and only return the items in it that derive from MyItem

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.