Select elements of certain type from list (c#)

2019-09-17 19:39发布

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 :/

标签: c# list oop
2条回答
疯言疯语
2楼-- · 2019-09-17 20:11

If I understand you correctly

form1.traps = form1.traps.OfType<Flame>()
             .Where(trap => trap.ID == ID && trap.pos <= pos)
             .ToList();
查看更多
可以哭但决不认输i
3楼-- · 2019-09-17 20:29

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;
}
查看更多
登录 后发表回答