Search code examples
c#dictionarylinq-to-sql

Datatable todictionary several columns


I'm trying to convert a datatable to a dictionary using the method described here, but I get an error

Cannot implicitly convert type System.Collections.Generic.Dictionary>' to 'System.Collections.Generic.Dictionary``.

This link helped, but only one value is pulled into the dictionary, not several which is what I need.

Thanks for any help.

public class MCEAV
{
    public int ID { get; set; }
    public int BOOK_ID { get; set; }
    public double DATA { get; set; }
}

Dictionary<int, MCEAV> dctGREEKS = new Dictionary<int, MCEAV>();
dctGREEKS = DATActx.MONTECARLO_EAVs.Select(Z => new { Z.ID, Z.BOOK_ID, Z.DATA}).ToDictionary(Z => Z.ID);

Solution

  • You need to specify the name of the class when using new else it is an anonymous type:

    dctGREEKS = DATActx.MONTECARLO_EAVs.Select(Z => 
                                   new MCEAV()
                                   { 
                                      ID = Z.ID, 
                                      BOOK_ID = Z.BOOK_ID, 
                                      DATA = Z.DATA
                                   }).ToDictionary(Z => Z.ID);
    

    So new { Z.ID, Z.BOOK_ID, Z.DATA} is an instance of an anonymous type created by the compiler while new MCEAV() is an instance of type MCEAV which is what you want for your dictionary.