redcodefinal
redcodefinal

Reputation: 909

C# Lists, Foreach, and Types

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.

Upvotes: 0

Views: 165

Answers (2)

Roman Starkov
Roman Starkov

Reputation: 61382

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;
    }
}

Upvotes: 3

O. R. Mapper
O. R. Mapper

Reputation: 20732

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.

Upvotes: 8

Related Questions