ncyankee
ncyankee

Reputation: 1258

DataReader with duplicate column names

What is the best way of handling trying to get data from a DataReader that has more than one column with the same name?

Because of the amount of work involved and because we don't want to lose support from a vendor by changing the stored procedures we are using to retrieve the data, I am trying to find another way to get access to a column that shows up more than once in a datareader without having to rewrite the stored procedures.

Any Ideas?

EDIT: Ok, the function that actually populates from a datareader is used in multiple places so there is a possibility that the function can be called by different stored procedures. What I did was to do a GetName using the index to check if it is the correct column, and if it is, then pull its value.

Upvotes: 1

Views: 2981

Answers (4)

mrrrk
mrrrk

Reputation: 2311

Based on original poster's approach described in the "Edit" paragraph, here's an extension method that will give the value based on the column name and the index of that name, e.g., 0 for the first instance of name, 1 for the second, etc:

using System;

namespace WhateverProject {

    internal static class Extentions {

        // If a query returns MULTIPLE columns with the SAME name, this allows us to get the Nth value of a given name.
        public static object NamedValue(this System.Data.IDataRecord reader, string name, int index) {
            if (string.IsNullOrWhiteSpace(name)) return null;
            if (reader == null) return null;
            var foundIndex = 0;
            for (var i = 0; i < reader.FieldCount; i++) {
                if (!reader.GetName(i).Equals(name, StringComparison.CurrentCultureIgnoreCase)) continue;
                if (index == foundIndex) return reader[i];
                foundIndex++;
            }
            return null;
        }
    }
}

Use it thus:

var value1 = reader.NamedValue("duplicatedColumnName", 0);
var value2 = reader.NamedValue("duplicatedColumnName", 1);

Upvotes: 1

user44702
user44702

Reputation: 83

You will have to reference the column by index no; i.e. reader[5].ToString(); to read the data in column 5.

Upvotes: 1

Matthew
Matthew

Reputation: 2072

If you know the index of the column, then access it by the index.

Upvotes: 3

Tom Ritter
Tom Ritter

Reputation: 101400

Can't you use column ordinals? 0 for the 1st, 1 for the 2nd, and so on?

Upvotes: 1

Related Questions