Search code examples
c#dapper

Dapper : reading into dictionary from readrer


my reader reads the contents from the stored procedure which has one of its 1st select statement as

 select id , name from FSubsystem

out of 10 select staments

and i declared the dictionary like below Dictionary SubsystemMApping = new Dictionary();

var reader = connection.QueryMultiple(...);

I need to read the fist select statement values to dictionary SubsystemMApping . id - to Key and name - to value

I tried doing it using reader.Read.Todictionary() but couldn't succeed . I am not very familier with Func & Action . dats the reason why i think i am not able to understand the 2 overloads of Todictionary properly.

Can anyone help ?


Solution

  • Imagine you have a POCO that's returned to you. Something like

    public class Item 
    {
       public int Id { get; set;}
       public string Name { get; set;}
    }
    

    Now imagine you have an IEnumerable<Item> and the collection is populated (this is most likely what Dapper is returning).

    To use the ToDictionary method, you have 2 important overloads.

    var dictionary = itemList.ToDictionary( item => item.Id );
    

    This returns a Dictionary<int,Item>. The key for the dictionary is each item.Id property.

    The key/value overload:

    var dictionary = itemList.ToDictionary( item => item.Id , item => item.Name );
    

    This overload creates a Dictionary<int,string> using the specified item.Id for key and item.Name for value.

    There are 2 more overloads that allow you to pass a custom comparer to be used when determining keys.