codeSMART

Entries from April 2008

Looping through SQL Server Tables Row by Row

April 30, 2008 · Leave a Comment

I needed to merge two table in SQL Server.  Found a simple tutorial on how to do it.  To be honest, the first method (implementing cursors) was fine for my purposes.

Link: http://www.sql-server-performance.com/articles/per/operations_no_cursors_p1.aspx

Categories: Other Development
Tagged:

Get Specific Object from an Array

April 29, 2008 · Leave a Comment

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)

Categories: Coding
Tagged:

Introduction to C# 3.0

April 29, 2008 · Leave a Comment

I learnt C# 1.0 back in the early part of this millenium, then changed jobs and concentrated on C++ and ANSI C (yes, I even bought a copy of Kernighan & Ritchie).  When I switched back to C# a couple of years ago, I basically had to re-teach myself all that I knew, and since C# 2.0 was in vogue then, that’s what I learnt.

Now, while I pride myself on being an early adopter in most areas, I have managed to successfully ignore C# 3.0 until now.  Honestly, who really needs LINQ anyway?

Oops!

I found some very informative talks from TechEd on MSDN’s Spotlight site recently which do a great job of highlighting the changes in C# 3.0 and introduce LINQ and Lamda Expressions in a really easy-to-digest format.  So easy that even I was forced to think, “Crap!  Why didn’t I get into this stuff sooner?”

Anyway, here are the links:

C# 3.0: Future Directions in Language Innovation
Anders Hejlsberg
http://www.microsoft.com/emea/msdn/spotlight/sessionh.aspx?videoid=319

Microsoft Visual C# Under the Covers: An In-Depth Look at C# 3.0
Luke Hoban
http://www.microsoft.com/emea/msdn/spotlight/sessionh.aspx?videoid=710

 

Categories: Coding
Tagged: , ,