0

I was wondering if there is a version of foreach that checks only for a specific type and returns it.

For example consider this class tree:

org.clixel.ClxBasic -> org.clixel.ClxObject -> org.clixel.ClxSprite -> WindowsGame1.test

Then consider this code

public List<ClxBasic> objects = new List<ClxBasic>();

foreach(GroupTester tester in objects)
{
    tester.GroupTesterOnlyProperty = true;
}

tester.GroupTesterOnlyProperty is a property created in GroupTester. Is there some way to make something like this work, like an overload of foreach, or another snippet that might help me? I want to make it easy for a programmer to sort through the lists grabbing only what type they need.

4
  • @Killercam: objects is already a List<T>, which implements the IEnumerable<T> interface. Commented Jun 26, 2012 at 9:16
  • GroupTester doesn't appear in your class hierarchy. How do you expect to cast 'objects' to an unrelated type ? Commented Jun 26, 2012 at 9:17
  • In this case why are you not using something like foreach(ClxBasic basic in objects) ...? Commented Jun 26, 2012 at 9:17
  • Oops, I meesed that up, GroupTester is related to ClxSprite. I meant to write it as Test and then make GroupTester be Test in the example. Commented Jun 26, 2012 at 9:20

2 Answers 2

8

You can use the OfType<T> extension method for IEnumerable<T> objects.

Your loop could then look like this:

foreach(GroupTester tester in objects.OfType<GroupTester>())
{
    tester.GroupTesterOnlyProperty = true;
}

Note: This assumes that GroupTester inherits from ClxBasic.

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

Comments

3
foreach(GroupTester tester in objects.OfType<GroupTester>())
{
    tester.GroupTesterOnlyProperty = true;
}

As suggested by @ThePower (and then deleted), you could iterate over all objects and check the type explicitly:

foreach(var tester in objects)
{
    if (tester is GroupTester)
    {
       (tester as GroupTester).GroupTesterOnlyProperty = true;
    }
}

5 Comments

Thank you! Works great! I'll keep this little snippet around for later use.
Aww change it back, the other one was very useful!
@user406470 I didn't change this in any way since I posted it :)
Weird, someone left an answer with a cool way to check the type of an object using if(x is ClxBasic)
@user406470 that is true; I've posted their answer so you can see it. I added the cast tester as GroupTester to make it work.

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.