20

I have a dynamic result from Dapper query that contains records like this:

{DapperRow, billing_currency_code = 'USD', count(*) = '6'}

I'm able to access 'USD' by using rowVariable.billing_currency_code

To get '6' value I tried rowVariable["count(*)"] and rowVariable.kv["count(*)"] and unfortunately nothing works...

I can't change the count(*) column name in my case

How to get the '6' value from the rowVariable of type DapperRow in such case?

Dale K
  • 25,246
  • 15
  • 42
  • 71
Zelid
  • 6,905
  • 11
  • 52
  • 76
  • I don't know the answer, but can't you use an alias in the query so you don't have 'count(*)', but a readable name instead? If you provide the query, I might be able to help. – Tsasken Aug 12 '14 at 12:00
  • No, unfortunately I can't add an alias or edit the query in any other way. – Zelid Aug 12 '14 at 12:13

2 Answers2

41

If the column name genuinely is "count(*)", then you can cast the row to a dictionary:

var data = (IDictionary<string,object>)row;
object value = data["count(*)"];

For that to work (at least, in SQL Server), your query would need to be something like:

select count(*) as [count(*)]

However, in most cases the column doesn't have a name, in which case: fix your query ;p

Actually, I'd probably say fix your query anyway; the following would be much easier to work with:

select count(*) as [Count]
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
12

Suppose Your Data as below

var Details={DapperRow, billing_currency_code = 'USD', count(*) = '6'}

as The columns is coming dynamically

var firstRow= Details.FirstOrDefault();

To get the heading columns of the data

var Heading= ((IDictionary<string, object>)firstRow).Keys.ToArray();

To get the value of the data by using key

var details = ((IDictionary<string, object>)firstRow);
var vallues= details[Heading[0]];
  • Nicely explained Example for beginners. – vibs2006 Jan 06 '20 at 08:14
  • Excellent answer. I was trying to get the properties of a dynamic (that was a DapperRow) and GetType().GetProperties() wasn't empty and TypeDescriptor.GetProperties() was returning double the values. – b.pell Oct 16 '20 at 15:43