Get Specific Object from an Array

For the last couple of years, I’ve been writing a program to decode DVB transport streams (more info at the Multiflex site), and have recently started implementing the decoding of H.264 (MPEG-4) video streams.

One challenge I have come across is to find the last instance of a certain class of object within an array of (generic) objects, for example to find the last instance of a class of type ‘Foo’ within ‘object[] args’.

Initially, I started with something like the following:

public Foo GetFoo(object[] args)
{
    for (int i = (args.Length - 1); i >= 0; i- -)
    {
        if (args[i] is Foo)
            return args[i] as Foo;
    }
    return null;
}

This is a bit messy, however.  Now that I have come to know and love C# 3.0, LINQ and Lamda Expressions, this can be distilled down to the following:

public Foo GetFoo(object[] args)
{
    try
    {
        return args.Last(c => c is Foo) as Foo;
    }
    catch
    {
        return null;
    }
}

Such elegance!!!

(BTW: The try/catch is in there because Last() will throw an Exception if no object of type Foo exists within args)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s