Select elements of certain type from list (c#)

2019-09-17 20:13发布

问题:

I have a list of "traps" in my main class. In the subclass "Flame" I want to delete certain elements from that list. The problem is, how do I select these elements? Trap does have other sublasses with different attributes.

This is what I got so far (code simplified, from "Flame.cs"):

public override Boolean collide()
{
    var flames = form1.traps.Where(trap => trap.ID == ID);
    foreach (Flame f in flames)
    {
        if (f.pos > pos)
        {
            form1.traps.Remove(f);
        }
    }
    return true;
}

I feel like I should know this, but atm I'm stuck :/

回答1:

You can use the OfType extension method.

public override Boolean collide()
{
    var flames = form1.traps.Where(trap => trap.ID == ID)
                            .OfType<Flame>()
                            .Where(f => f.pos > pos)
                            .ToList();

    foreach (Flame flame in flames)
    {
        form1.traps.Remove(flame);
    }

    return true;
}


回答2:

If I understand you correctly

form1.traps = form1.traps.OfType<Flame>()
             .Where(trap => trap.ID == ID && trap.pos <= pos)
             .ToList();


标签: c# list oop