Thursday, October 21, 2010

The March of Progress, .NET-Style

A fairly common programming task is the need to convert from an array of integers to a comma-separated string.  For instance, this often comes up when you have an array containing some IDs, and you want to use the IDs in a SQL query (such as "select * from some_table where id in (1, 2, 3)").  In the old .NET 2.0, this usually involved a "For" loop:

    Dim intArray() As Integer = New Integer() {1, 2, 3}
    Dim s As String = ""
    For Each id As Integer in intArray
        s &= id.ToString() & ","
    s = s.Substring(0, s.Length - 1)

Then came .NET 3.5 and LINQ, and the code got a bit more concise:

    Dim idStrs As IEnumerable(Of String) = _
        From id In intArray Select idStr = id.ToString()
    Dim s As String = String.Join(",", idStrs.ToArray())

Finally .NET 4.0 came along with a helpful new form of the String.Join method, and reduced this task to a one-liner:

   Dim s As String = String.Join(",", intArray)

Someone up there is listening.

No comments:

Post a Comment