Check column exists in SqlReader using Linq

The only way to check if a column exists in a SqlDataReader is by looping through the columns

http://stackoverflow.com/questions/373230/check-for-column-name-in-a-sqldatareader-object

can anyone give me some linq to do this so I can put the check in a single statement?
purplesoupAsked:
Who is Participating?
 
NavneetSoftware EngineerCommented:
Hi!

add this class
    static  class MyName
    {

        /// <summary>
        /// Checks if a column exists in the DataReader
        /// </summary>
        /// <param name="dr">DataReader</param>
        /// <param name="ColumnName">Name of the column to find</param>
        /// <returns>Returns true if the column exists in the DataReader, else returns false</returns>
        public static Boolean ColumnExists(this IDataReader dr, String ColumnName)
        {
            for (Int32 i = 0; i < dr.FieldCount; i++)
                if (dr.GetName(i).Equals(ColumnName, StringComparison.OrdinalIgnoreCase))
                    return true;

            return false;
        }
    }

Open in new window


Adding above extension to IDataReader
check your sqlDataReader for Column like :

sqlDataReader.ColumnExists("Sequence");

Thanks!
0
 
NavneetSoftware EngineerCommented:
HI!

You can try this as well

if (reader.GetSchemaTable().Columns["COLUMNNAME"] != null)


Thanks!

0
 
purplesoupAuthor Commented:
This isn't quite right is it - the SchemaTable returned is a table about the resultset, and the columns are ColumnName, ColumnOrdinal, ColumnSize etc, so it will only tell me about the columns in the schema table, not the columns in the resultset.

If for example I want to know if a column called "Sequence" is in my result set,

if (reader.GetSchemaTable().Columns["Sequence"] != null)

won't do it.
0
 
purplesoupAuthor Commented:
That's pretty clever - I'll wait a little longer if you don't mind just to see if anyone comes up with anything as good...
0
 
purplesoupAuthor Commented:
Sorry - I didn't actually intend to wait quite so long..
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.