How to use Dapper and return a dictionary from the query?

c# dapper


my sql is :

select (select count(*) from TblRMember where sex=1) male,
 (select count(*) from TblRMember where sex=2) female,
 (select count(*) from TblRMember where sex=0) unkown

I want Dapper.Net to return a Dictinary like this:


I have see How to map to a Dictionary object from database results using Dapper Dot Net? ,but that can not work!

How to use ToDictionary or other way to implement I want

var myDictionary = sqlConnection.Query(strSql).ToDictionary(??);


5/23/2017 10:27:58 AM

Accepted Answer

First change your query to be single one:

select case when sex = 1 then 'male'
            when sex = 2 then 'female'
            when sex = 0 then 'unknown'
       end as sex, count(*) as cnt
from TblRMember
group by sex

as I see sex is numerical, so you either have to select by coumn with name (sexname?) or change it in your code. After that:

var myDictionary = sqlConnection.Query(strSql)
                    .ToDictionary(x =>, x => (int)x.cnt);
7/18/2013 7:48:26 AM

Popular Answer

string strSql = "SELECT DISTINCT TableID AS [Key],TableName AS [Value] FROM dbo.TS_TStuctMaster";
Dictionary<string,string> dicts = sqlConnection.Query<KeyValuePair<string,string>>(strSql).ToDictionary(pair => pair.Key, pair => pair.Value);

You can use aliases and strong types.

Aliases are the key points, which match the attributes of KeyValuePair type Key and Value.

It works under strong typing and runs well.

I don't like dynamic type. It brings disaster in certain situations. Moreover, the boxing and unboxing brings performance loss.

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow