Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting if an IDataReader contains a certain field before iteration [duplicate]

Tags:

c#

So I'm using an IDataReader to hydrate some business objects, but I don't know at runtime exactly what fields will be in the reader. Any fields that aren't in the reader would be left null on the resulting object. How do you test if a reader contains a specific field without just wrapping it in a try/catch?

like image 523
JC Grubbs Avatar asked Sep 09 '08 21:09

JC Grubbs


2 Answers

This should do the trick:

    Public Shared Function ReaderContainsColumn(ByVal reader As IDataReader, ByVal name As String) As Boolean
        For i As Integer = 0 To reader.FieldCount - 1
            If reader.GetName(i).Equals(name, StringComparison.CurrentCultureIgnoreCase) Then Return True
        Next
        Return False
    End Function

or (in C#)

public static bool ReaderContainsColumn(IDataReader reader, string name)
{
    for (int i = 0; i < reader.FieldCount; i++) {
        if (reader.GetName(i).Equals(name, StringComparison.CurrentCultureIgnoreCase)) return true; 
    }
    return false;
}

:o)

like image 149
mrrrk Avatar answered Sep 27 '22 19:09

mrrrk


You can also use IDataReader.GetSchemaTable to get a list of all the columns in the reader.

http://support.microsoft.com/kb/310107

like image 38
Tadmas Avatar answered Sep 27 '22 20:09

Tadmas